package com.mingqijia.gassafety.statistics.service.impl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mingqijia.gassafety.authority.api.resp.config.DictionaryItemRespDTO;
import com.mingqijia.gassafety.authority.dal.helper.ConfigureHolder;
import com.mingqijia.gassafety.db.entity.*;

import com.mingqijia.gassafety.db.entity.auth.CompanyEntry;
import com.mingqijia.gassafety.db.entity.vo.PlatformBrandDetailResp;
import com.mingqijia.gassafety.db.entity.vo.PlatformEquipmentResp;
import com.mingqijia.gassafety.db.entity.vo.SpMapVo;

import com.mingqijia.gassafety.db.entity.vo.*;

import com.mingqijia.gassafety.db.mapper.*;
import com.mingqijia.gassafety.db.mapper.auth.CompanyMapper;
import com.mingqijia.gassafety.shared.constant.EquipmentType;
import com.mingqijia.gassafety.shared.user.UserBackend;
import com.mingqijia.gassafety.shared.utils.ApplicationUtils;
import com.mingqijia.gassafety.shared.utils.commonUtils.PageUtil;
import com.mingqijia.gassafety.shared.vcc.VccAuthoritiesProvider;
import com.mingqijia.gassafety.statistics.constant.ScreenStatisticsAlarmTypeEnum;
import com.mingqijia.gassafety.statistics.constant.ScreenStatisticsAreaEnum;
import com.mingqijia.gassafety.statistics.request.ScreenCompanyManageReq;
import com.mingqijia.gassafety.statistics.request.ScreenStatisticsAreaReq;
import com.mingqijia.gassafety.statistics.request.ScreenStatisticsMOrGReq;
import com.mingqijia.gassafety.statistics.request.ScreenStatisticsReq;
import com.mingqijia.gassafety.statistics.response.*;
import com.mingqijia.gassafety.statistics.service.ScreenStatisticsService;
import com.mingqijia.gassafety.webserver.feign.ConsoleSkFeignClient;
import com.mingqijia.gassafety.webserver.request.console.sk.ConsoleSkDeviceRunListRequest;
import com.mingqijia.gassafety.webserver.request.console.sk.ConsoleSkRecordsRequest;
import com.mingqijia.gassafety.webserver.response.sk.*;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.function.ToIntFunction;
import java.util.stream.Collectors;


@Slf4j
@Service
public class ScreenStatisticsServiceImpl implements ScreenStatisticsService {

    @Autowired
    private CmJoinInfoMapper cmJoinInfoMapper;

    @Autowired
    private CmStatDeviceMapper cmStatDeviceMapper;

    @Autowired
    private CmStatDevicealarmMapper cmStatDevicealarmMapper;

    @Autowired
    private ConfigureHolder holder;

    @Autowired
    private HistoryAlarmMapper historyAlarmMapper;

    @Autowired
    private HistoryBrokenMapper historyBrokenMapper;

    @Autowired
    private DtuMapper dtuMapper;

    @Autowired
    private VccAuthoritiesProvider provider;

    @Autowired
    private ConsoleSkFeignClient consoleSkFeignClient;

    @Autowired
    private DeviceStateMapper deviceStateMapper;

    @Autowired
    private CompanyMapper companyMapper;

    @Autowired
    private JvInfoMapper jvInfoMapper;

    @Value(value = "${gassafety.ewt.url}")
    public String targetUrl;

    //过滤企业对应orgcode格式为  orgcode,orgcode
    @Value(value = "${gassafety.belong.orgCode:}")
    private String belongOrgCode;

    @Override
    public PlatformApplySituationResponse platformApply(ScreenStatisticsReq req) {
        PlatformApplySituationResponse response = new PlatformApplySituationResponse();
        List<String> spIds = areaPermission();
        log.info("当前企业的值为:{}", spIds);
        QueryWrapper<CmJoinInfo> queryWrapper = new QueryWrapper<>();

        if (req.getGroupScreen() == 2) {
            queryWrapper.lambda().in(CmJoinInfo::getId, spIds);
        }

        if( StringUtils.isNotEmpty(belongOrgCode) ){
            //根据orgcode批量查询企业信息
            String[] spIdCode = belongOrgCode.split(",");
            List<String> orgCodes = Arrays.stream(spIdCode).collect(Collectors.toList());
            List<SpMapVo> spMapVoList = dtuMapper.querySGSpIdOrgCode(orgCodes);
            //韶关存在多个子企业需要归属到韶关燃气企业
            //List<SpMapVo> spMapVos = dtuMapper.querySGSpIdMap(belongOrgCode);
            if( spMapVoList.size()>0 ){
                List<String> unCountSpIds = spMapVoList.stream().map(SpMapVo::getSpId).collect(Collectors.toList());
                queryWrapper.lambda().notIn(CmJoinInfo::getId, unCountSpIds);
            }
        }

        queryWrapper.lambda().orderByDesc(CmJoinInfo::getUpdateTime);
        List<CmJoinInfo> joinInfos = cmJoinInfoMapper.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(joinInfos)) {
            response.setOrgCount(joinInfos.size());
            response.setUpdateTime(joinInfos.get(0).getUpdateTime());
            if (req.getGroupScreen() == 2) {
                response.setRegionId(joinInfos.get(0).getRegionId());
                response.setRegionName(ScreenStatisticsAreaEnum.getStateName(joinInfos.get(0).getRegionId()));
            }
        }
        List<CmStatDevice> cmStatDevices;
        if (req.getGroupScreen() == 2) {
            cmStatDevices = cmStatDeviceMapper.selectPlatformImeiBySpId(spIds);
        } else {
            cmStatDevices = cmStatDeviceMapper.selectPlatformImeiBySpId(null);
        }
        //设备接入总数
        Integer dtuCount = 0;
        //民用设备数量
        Integer civilDtuCount = 0;
        //工商业设备数量
        Integer industryDtuCount = 0;
        if (CollectionUtils.isNotEmpty(cmStatDevices)) {
            for (CmStatDevice cmStatDevice : cmStatDevices) {
                dtuCount = dtuCount + cmStatDevice.getTotalDevice();
                if (StringUtils.equals("1", cmStatDevice.getMyType())) {
                    civilDtuCount = civilDtuCount + cmStatDevice.getTotalDevice();
                }else {
                    industryDtuCount = industryDtuCount + cmStatDevice.getTotalDevice();
                }
                if (response != null && response.getUpdateTime() != null) {
                    if (response.getUpdateTime().before(cmStatDevice.getCreateTime())) {
                        response.setUpdateTime(cmStatDevice.getCreateTime());
                    }
                } else {
                    response.setUpdateTime(cmStatDevice.getCreateTime());
                }
            }
        }
        response.setDtuCount(dtuCount);
        response.setCivilDtuCount(civilDtuCount);
        response.setIndustryDtuCount(industryDtuCount);
        log.info("平台应用情况的数据为:{}", response);
        return response;
    }

    @Override
    public List<PlatformApplyListResponse> platformApplyList() {
        List<PlatformApplyListResponse> listResponses = new ArrayList<>();
        List<String> spIds = areaPermission();
        QueryWrapper<CmJoinInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().in(CmJoinInfo::getId, spIds);
        if( StringUtils.isNotEmpty(belongOrgCode) ){
            //根据orgcode批量查询企业信息
            String[] spIdCode = belongOrgCode.split(",");
            List<String> orgCodes = Arrays.stream(spIdCode).collect(Collectors.toList());
            List<SpMapVo> spMapVoList = dtuMapper.querySGSpIdOrgCode(orgCodes);
            //韶关存在多个子企业需要归属到韶关燃气企业
            //List<SpMapVo> spMapVos = dtuMapper.querySGSpIdMap(belongOrgCode);
            if( spMapVoList.size()>0 ){
                List<String> unCountSpIds = spMapVoList.stream().map(SpMapVo::getSpId).collect(Collectors.toList());
                queryWrapper.lambda().notIn(CmJoinInfo::getId, unCountSpIds);
            }
        }
        List<CmJoinInfo> joinInfos = cmJoinInfoMapper.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(joinInfos)) {
            for (CmJoinInfo joinInfo : joinInfos) {
                PlatformApplyListResponse response = new PlatformApplyListResponse();
                BeanUtils.copyProperties(joinInfo, response);
                response.setSpId(joinInfo.getId());
                response.setRegionName(ScreenStatisticsAreaEnum.getStateName(joinInfo.getRegionId()));
                listResponses.add(response);
            }
        }
        return listResponses;
    }

    @Override
    public List<PlatformApplyListResponse> platformAreaList() {
        List<PlatformApplyListResponse> listResponses = new ArrayList<>();
        List<CmJoinInfo> joinInfos = cmJoinInfoMapper.selectList(null);
        if (CollectionUtils.isNotEmpty(joinInfos)) {
            Map<Integer, List<CmJoinInfo>> cmJoinMap = joinInfos.stream().collect(Collectors.groupingBy(CmJoinInfo::getRegionId));
            for (Integer regionId : cmJoinMap.keySet()) {
                PlatformApplyListResponse response = new PlatformApplyListResponse();
                response.setRegionId(regionId);
                response.setRegionName(ScreenStatisticsAreaEnum.getStateName(regionId));
                if (cmJoinMap.containsKey(regionId)) {
                    List<CmJoinInfo> cmJoinInfos = cmJoinMap.get(regionId);
                    response.setLon(cmJoinInfos.get(0).getLon());
                    response.setLat(cmJoinInfos.get(0).getLat());
                }
                listResponses.add(response);
            }
        }
        return listResponses;
    }

    @Override
    public PlatformPopupResponse platformPopop(ScreenStatisticsReq req) {
        PlatformPopupResponse response = new PlatformPopupResponse();
        QueryWrapper<CmJoinInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CmJoinInfo::getId, req.getSpId());
        List<CmJoinInfo> joinInfos = cmJoinInfoMapper.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(joinInfos)) {
            Integer userNums = 0;
            for (CmJoinInfo joinInfo : joinInfos) {
                userNums = userNums + joinInfo.getGsscUserNums() + joinInfo.getSkUserNums();
            }
            response.setId(joinInfos.get(0).getId());
            response.setSpName(joinInfos.get(0).getSpName());
            response.setUserNums(userNums);
            response.setRegionId(joinInfos.get(0).getRegionId());
            response.setRegionName(ScreenStatisticsAreaEnum.getStateName(joinInfos.get(0).getRegionId()));
        }
//        LocalDate currentDate = LocalDate.now();
//        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
//        String formattedDate = currentDate.format(formatter);
        List<String> spIds = new ArrayList<>();
        spIds.add(req.getSpId());
        List<CmStatDevice> cmStatDevices = cmStatDeviceMapper.selectPlatformImeiBySpId(spIds);
        if (CollectionUtils.isNotEmpty(cmStatDevices)) {
            //设备总数
            Integer totalDevice = 0;
            //民用设备数量
            Integer civilNums = 0;
            //工商业设备数量
            Integer industrySums = 0;
            //品牌厂家数量
            List<String> brands = new ArrayList<>();
            for (CmStatDevice cmStatDevice : cmStatDevices) {
                totalDevice = totalDevice + cmStatDevice.getTotalDevice();
                if (StringUtils.equals(cmStatDevice.getMyType(), "1")) {
                    civilNums = civilNums + cmStatDevice.getTotalDevice();
                }
                else {
                    industrySums = industrySums + cmStatDevice.getTotalDevice();
                }
                if (!brands.contains(cmStatDevice.getEsCode())) {
                    brands.add(cmStatDevice.getEsCode());
                }
            }
            response.setTotalDevice(totalDevice);
            response.setCivilNums(civilNums);
            response.setIndustrySums(industrySums);
            response.setBrandSums(brands.size());
        } else {
            response.setTotalDevice(0);
            response.setCivilNums(0);
            response.setIndustrySums(0);
            response.setBrandSums(0);
        }

        List<CmStatDevicealarm> devicealarms = cmStatDevicealarmMapper.queryPlatformImeiBySpId(spIds);
        if (CollectionUtils.isNotEmpty(devicealarms)) {
            //告警数量
            Integer totalDevice = 0;
            //总量
            Integer totalAlarm = 0;
            //已处理告警数量
            Integer processingCount = 0;
            for (CmStatDevicealarm devicealarm : devicealarms) {
                totalDevice = totalDevice + devicealarm.getTotalAlarm();
                totalAlarm = totalAlarm + devicealarm.getTotalAlarm();
                processingCount = processingCount + devicealarm.getTotalAlarmProcessing();
            }
            response.setTotalAlarm(totalDevice);
            if (totalAlarm == 0) {
                response.setProcessingRatio("0");
            } else {
                BigDecimal divide = new BigDecimal(processingCount).divide(new BigDecimal(totalAlarm), 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);
                response.setProcessingRatio(divide + "%");
            }

        } else {
            response.setTotalAlarm(0);
            response.setProcessingRatio("0");
        }
        return response;
    }

    @Override
    public PlatformPopupResponse platformAreaPopop(ScreenStatisticsAreaReq req) {
        PlatformPopupResponse response = new PlatformPopupResponse();
        QueryWrapper<CmJoinInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CmJoinInfo::getRegionId, req.getRegionId());
        List<CmJoinInfo> joinInfos = cmJoinInfoMapper.selectList(queryWrapper);
        List<String> spIds = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(joinInfos)) {
            Integer userNums = 0;
            for (CmJoinInfo joinInfo : joinInfos) {
                userNums = userNums + joinInfo.getGsscUserNums() + joinInfo.getSkUserNums();
                spIds.add(joinInfo.getId());
            }
            response.setUserNums(userNums);
            response.setRegionId(joinInfos.get(0).getRegionId());
            response.setRegionName(ScreenStatisticsAreaEnum.getStateName(joinInfos.get(0).getRegionId()));
        } else {
            response.setUserNums(0);
            response.setRegionId(req.getRegionId());
            response.setRegionName(ScreenStatisticsAreaEnum.getStateName(req.getRegionId()));
        }
//        LocalDate currentDate = LocalDate.now();
//        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
//        String formattedDate = currentDate.format(formatter);
        if (CollectionUtils.isNotEmpty(spIds)) {
            List<CmStatDevice> cmStatDevices = cmStatDeviceMapper.selectPlatformImeiBySpId(spIds);
            if (CollectionUtils.isNotEmpty(cmStatDevices)) {
                //设备总数
                Integer totalDevice = 0;
                //民用设备数量
                Integer civilNums = 0;
                //工商业设备数量
                Integer industrySums = 0;
                //品牌厂家数量
                List<String> brands = new ArrayList<>();
                for (CmStatDevice cmStatDevice : cmStatDevices) {
                    totalDevice = totalDevice + cmStatDevice.getTotalDevice();
                    if (StringUtils.equals(cmStatDevice.getMyType(), "1")) {
                        civilNums = civilNums + cmStatDevice.getTotalDevice();
                    }
                    else {
                        industrySums = industrySums + cmStatDevice.getTotalDevice();
                    }
                    if (!brands.contains(cmStatDevice.getEsCode())) {
                        brands.add(cmStatDevice.getEsCode());
                    }
                }
                response.setTotalDevice(totalDevice);
                response.setCivilNums(civilNums);
                response.setIndustrySums(industrySums);
                response.setBrandSums(brands.size());
            } else {
                response.setTotalDevice(0);
                response.setCivilNums(0);
                response.setIndustrySums(0);
                response.setBrandSums(0);
            }

            List<CmStatDevicealarm> devicealarms = cmStatDevicealarmMapper.queryPlatformImeiBySpId(spIds);
            if (CollectionUtils.isNotEmpty(devicealarms)) {
                //告警数量
                Integer totalDevice = 0;
                //总量
                Integer totalAlarm = 0;
                //已处理告警数量
                Integer processingCount = 0;
                for (CmStatDevicealarm devicealarm : devicealarms) {
                    totalDevice = totalDevice + devicealarm.getTotalAlarm();
                    totalAlarm = totalAlarm + devicealarm.getTotalAlarm();
                    processingCount = processingCount + devicealarm.getTotalAlarmProcessing();
                }
                response.setTotalAlarm(totalDevice);
                if (totalAlarm == 0) {
                    response.setProcessingRatio("0");
                } else {
                    BigDecimal divide = new BigDecimal(processingCount).divide(new BigDecimal(totalAlarm), 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);
                    response.setProcessingRatio(divide + "%");
                }

            } else {
                response.setTotalAlarm(0);
                response.setProcessingRatio("0");
            }
        } else {
            response.setTotalDevice(0);
            response.setCivilNums(0);
            response.setIndustrySums(0);
            response.setTotalAlarm(0);
            response.setBrandSums(0);
            response.setProcessingRatio("0");
        }

        return response;
    }

    @Override
    public List<PlatformBrandDetailResp> platformBrand(ScreenStatisticsReq req) {
        List<String> spIds = new ArrayList<>();
        if (req.getGroupScreen() ==2) {
            spIds = areaPermission();
        } else {
            List<CmJoinInfo> joinInfoList = cmJoinInfoMapper.selectList(null);
            if (CollectionUtils.isNotEmpty(joinInfoList)) {
                spIds = joinInfoList.stream().map(CmJoinInfo::getId).collect(Collectors.toList());
            }
        }
        List<PlatformBrandDetailResp> brandDetailResps = cmStatDeviceMapper.selectPlatformBrandBySpId(spIds);
        //根据设备数量降序
        brandDetailResps = brandDetailResps.stream().sorted(Comparator.comparing(PlatformBrandDetailResp::getEsNum,Comparator.nullsLast(Comparator.reverseOrder()))).collect(Collectors.toList());

        return brandDetailResps;
    }

    @Override
    public List<PlatformBrandDetailResp> groupPlatformBrand() {
        List<String> spIds = new ArrayList<>();
        List<CmJoinInfo> joinInfoList = cmJoinInfoMapper.selectList(null);
        if (CollectionUtils.isNotEmpty(joinInfoList)) {
            spIds = joinInfoList.stream().map(CmJoinInfo::getId).collect(Collectors.toList());
        }
        List<PlatformBrandDetailResp> brandDetailResps = cmStatDeviceMapper.selectPlatformBrandBySpId(spIds);
        //根据设备数量降序
        brandDetailResps = brandDetailResps.stream().sorted(Comparator.comparing(PlatformBrandDetailResp::getEsNum,Comparator.nullsLast(Comparator.reverseOrder()))).collect(Collectors.toList());

        return brandDetailResps;
    }

    @Override
    public List<PlatformEquipmentResp> platformEquipment(ScreenStatisticsReq req) {
        List<PlatformEquipmentResp> respList = new ArrayList<>();
        List<String> spIds = new ArrayList<>();
        if (req.getGroupScreen() == 2) {
            spIds = areaPermission();
        }else {
            List<CmJoinInfo> joinInfoList = cmJoinInfoMapper.selectList(null);
            if (CollectionUtils.isNotEmpty(joinInfoList)) {
                spIds = joinInfoList.stream().map(CmJoinInfo::getId).collect(Collectors.toList());
            }
        }
        List<PlatformEquipmentResp> equipmentResps = cmStatDeviceMapper.selectPlatformEquipmentBySpId(spIds);
        List<String> deviceTypes = Arrays.asList("Gas_alarm_controller", "Independent_gas_detector", "Point_type_gas_detector");
        if (CollectionUtils.isNotEmpty(equipmentResps)) {
            PlatformEquipmentResp platformEquipmentResp = new PlatformEquipmentResp();
            platformEquipmentResp.setDeviceType("industry");
            platformEquipmentResp.setTypeName("工商业燃气报警器");
            platformEquipmentResp.setDeviceNum(0);
            for (PlatformEquipmentResp equipmentResp : equipmentResps) {
                if (deviceTypes.contains(equipmentResp.getDeviceType())) {
                    platformEquipmentResp.setDeviceNum(platformEquipmentResp.getDeviceNum() + equipmentResp.getDeviceNum());
                } else {
                    PlatformEquipmentResp resp = new PlatformEquipmentResp();
                    BeanUtils.copyProperties(equipmentResp, resp);
                    respList.add(resp);
                }
            }
            respList.add(platformEquipmentResp);
        }
        //根据设备数量降序
        respList = respList.stream().sorted(Comparator.comparing(PlatformEquipmentResp::getDeviceNum,Comparator.nullsLast(Comparator.reverseOrder()))).collect(Collectors.toList());

        return respList;
    }

    @Override
    public List<PlatformAlarmDataResp> platformAlarmData(ScreenStatisticsReq req) {
        List<PlatformAlarmDataResp> respList = new ArrayList<>();
        List<String> spIds = areaPermission();
        List<String> imeiList = new ArrayList<>();
        List<String> spIdLists = new ArrayList<>();
        //查询所有企业数据
        Map<String, CmJoinInfo> cmJoinInfoMap = new HashMap<>();
        StringBuffer sb = new StringBuffer();
        if (req.getGroupScreen() == 2) {
            QueryWrapper<CmJoinInfo> queryCmJoinWrapper = new QueryWrapper<>();
            queryCmJoinWrapper.lambda().in(CmJoinInfo::getId, spIds);
            //查询区域所有企业
            List<CmJoinInfo> cmJoinInfos = cmJoinInfoMapper.selectList(queryCmJoinWrapper);
            if (CollectionUtils.isNotEmpty(cmJoinInfos)) {
                for (CmJoinInfo cmJoinInfo : cmJoinInfos) {
                    cmJoinInfoMap.put(cmJoinInfo.getId(), cmJoinInfo);
                    sb.append(cmJoinInfo.getId()).append(",");
                    spIdLists.add(cmJoinInfo.getId());
                }
            } else {
                spIdLists = null;
            }
        } else {
            List<CmJoinInfo> cmJoinInfos = cmJoinInfoMapper.selectList(null);
            if (CollectionUtils.isNotEmpty(cmJoinInfos)) {
                for (CmJoinInfo cmJoinInfo : cmJoinInfos) {
                    cmJoinInfoMap.put(cmJoinInfo.getId(), cmJoinInfo);
                    sb.append(cmJoinInfo.getId()).append(",");
                    spIdLists.add(cmJoinInfo.getId());
                }
            }
        }
        //查询前10条告警记录
        List<HistoryAlarm> historyAlarms = historyAlarmMapper.queryAlarm(spIdLists);
        if (CollectionUtils.isNotEmpty(historyAlarms)) {
            for (HistoryAlarm historyAlarm : historyAlarms) {
                imeiList.add(historyAlarm.getIMEI());
                PlatformAlarmDataResp resp = new PlatformAlarmDataResp();
                resp.setImei(historyAlarm.getIMEI());
                resp.setAlarmType("燃气泄露");
                resp.setSpId(historyAlarm.getSpId());
                resp.setCreateTime(historyAlarm.getCreatedAt());
                resp.setAppealTime(historyAlarm.getAppealTime());
                if (historyAlarm.getAppealStatus() == 0) {
                    resp.setDisposeStatus("未处理");
                    resp.setDisposeRatio("0");
                }else if (historyAlarm.getAppealStatus() == 1) {
                    resp.setDisposeStatus("转工单处理");
                    if (historyAlarm.getAppealTime() != null && historyAlarm.getCreatedAt() != null) {
                        long millise = (historyAlarm.getAppealTime().getTime() - historyAlarm.getCreatedAt().getTime()) / 60000;
                        if (millise > 30) {
                            resp.setDisposeRatio("0");
                        } else {
                            resp.setDisposeRatio("50");
                        }
                    } else {
                        resp.setDisposeRatio("50");
                    }
                }else {
                    resp.setDisposeStatus("已处理");
                    long millise = (historyAlarm.getAppealTime().getTime() - historyAlarm.getCreatedAt().getTime()) / 60000;
                    if (millise > 30) {
                        resp.setDisposeRatio("0");
                    } else {
                        resp.setDisposeRatio("100");
                    }
                }
                respList.add(resp);
            }
        }

        //查询客户数据
        Map<String, String> dtuMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(imeiList)) {
            QueryWrapper<Dtu> consumerWrapper = new QueryWrapper<>();
            consumerWrapper.lambda().in(Dtu::getIMEI, imeiList)
                    .eq(Dtu::getIsDeleted, 0);
            List<Dtu> dtuList = dtuMapper.selectList(consumerWrapper);
            if (CollectionUtils.isNotEmpty(dtuList)) {
                dtuMap = dtuList.stream().collect(Collectors.toMap(Dtu::getIMEI, Dtu::getEquipmentType));
            }
        }
        Map<String, SpMapVo> mapVoMap = new HashMap<>();
        if( StringUtils.isNotEmpty(belongOrgCode) ){
            //根据orgcode批量查询企业信息
            String[] spIdCode = belongOrgCode.split(",");
            List<String> orgCodes = Arrays.stream(spIdCode).collect(Collectors.toList());
            List<SpMapVo> spMapVoList = dtuMapper.querySGSpIdOrgCode(orgCodes);
            //韶关存在多个子企业需要归属到韶关燃气企业
            //List<SpMapVo> spMapVos = dtuMapper.querySGSpIdMap(belongOrgCode);
            if( spMapVoList.size()>0 ){
                mapVoMap = spMapVoList.stream().collect(Collectors.toMap(SpMapVo::getSpId, SpMapVo -> SpMapVo));
            }
        }
        for (PlatformAlarmDataResp alarmDataResp : respList) {
            if (cmJoinInfoMap.containsKey(alarmDataResp.getSpId())) {
                CmJoinInfo cmJoinInfo = cmJoinInfoMap.get(alarmDataResp.getSpId());
                if (mapVoMap.containsKey(alarmDataResp.getSpId())) {
                    SpMapVo spMapVo = mapVoMap.get(alarmDataResp.getSpId());
                    alarmDataResp.setSpId(spMapVo.getPSpId());
                    alarmDataResp.setSpName(spMapVo.getPSpName());
                } else {
                    alarmDataResp.setSpId(cmJoinInfo.getId());
                    alarmDataResp.setSpName(cmJoinInfo.getSpName());
                }
                alarmDataResp.setRegionId(cmJoinInfo.getRegionId());
                alarmDataResp.setLat(cmJoinInfo.getLat());
                alarmDataResp.setLon(cmJoinInfo.getLon());
                if (cmJoinInfo.getRegionId() != null) {
                    alarmDataResp.setRegionName(ScreenStatisticsAreaEnum.getStateName(cmJoinInfo.getRegionId()));
                }
            }
            if (dtuMap.containsKey(alarmDataResp.getImei())) {
                if (StringUtils.equals(EquipmentType.HOME_GAS_DETECTOR.getCode(), dtuMap.get(alarmDataResp.getImei()))) {
                    alarmDataResp.setMyType(1);
                    alarmDataResp.setMyName("民用");
                }else {
                    alarmDataResp.setMyType(2);
                    alarmDataResp.setMyName("工商业");
                }
            }
        }
        // 查询厨房的数据
        if (StringUtils.isNotEmpty(sb)) {
            ConsoleSkRecordsRequest request = new ConsoleSkRecordsRequest();
            request.setPage(1);
            request.setPageSize(10);
            request.setSpId(sb.toString().substring(0, sb.toString().length() - 1));
            request.setDataType("1");
            log.info("新增大屏查询报警信息列表请求:{}", JSONUtil.toJsonStr(request));
            ConsoleSkRecordsResponse response = consoleSkFeignClient
                    .alarmSOSRecords(request);
            log.info("新增大屏查询报警信息列表响应:{}", JSONUtil.toJsonStr(response));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (response != null && response.getCode() == 0 && response.getData() != null && CollectionUtils.isNotEmpty(response.getData().getList())) {
                for (ConsoleSkRecordsList skRecordsList : response.getData().getList()) {
                    PlatformAlarmDataResp resp = new PlatformAlarmDataResp();
                    resp.setImei(skRecordsList.getDeviceId());
                    if (cmJoinInfoMap.containsKey(skRecordsList.getSpId())) {
                        CmJoinInfo cmJoinInfo = cmJoinInfoMap.get(skRecordsList.getSpId());
                        resp.setRegionId(cmJoinInfo.getRegionId());
                        resp.setLat(cmJoinInfo.getLat());
                        resp.setLon(cmJoinInfo.getLon());
                        if (mapVoMap.containsKey(resp.getSpId())) {
                            SpMapVo spMapVo = mapVoMap.get(resp.getSpId());
                            resp.setSpId(spMapVo.getPSpId());
                            resp.setSpName(spMapVo.getPSpName());
                        } else {
                            resp.setSpId(cmJoinInfo.getId());
                            resp.setSpName(cmJoinInfo.getSpName());
                        }
                        if (cmJoinInfo.getRegionId() != null) {
                            resp.setRegionName(ScreenStatisticsAreaEnum.getStateName(cmJoinInfo.getRegionId()));
                        }
                    }
                    resp.setMyType(1);
                    resp.setMyName("民用");
                    resp.setAlarmType(ScreenStatisticsAlarmTypeEnum.getStateName(skRecordsList.getAlarmType()));
                    if (skRecordsList.getDealStatus() == 0) {
                        resp.setDisposeStatus("未处理");
                    } else if (skRecordsList.getDealStatus() == 1 || skRecordsList.getDealStatus() == 5 || skRecordsList.getDealStatus() == 6) {
                        resp.setDisposeStatus("转工单处理");
                    } else {
                        resp.setDisposeStatus("已处理");
                    }
                    resp.setDisposeRatio(skRecordsList.getProcessingRate() + "");

                    try {
                        if (StringUtils.isNotEmpty(skRecordsList.getAlarmEndTime())) {
                            resp.setCreateTime(sdf.parse(skRecordsList.getAlarmEndTime()));
                        } else {
                            resp.setCreateTime(sdf.parse(skRecordsList.getAlarmTime()));
                        }
                        if (StringUtils.isNotEmpty(skRecordsList.getResultTime())) {
                            resp.setAppealTime(sdf.parse(skRecordsList.getResultTime()));
                        }
                    } catch (Exception e) {
                        log.error("时间转换错误:{}", e);
                    }
                    respList.add(resp);
                }
            }
        }
        respList = respList.stream().sorted(Comparator.comparing(PlatformAlarmDataResp::getCreateTime,Comparator.nullsLast(Comparator.reverseOrder()))).collect(Collectors.toList());
        // 取前10个元素
        List<PlatformAlarmDataResp> top5 = respList.subList(0, Math.min(10, respList.size()));
        return top5;
    }

    @Override
    public AlarmSituationResp platformAlarmSituation() {
        AlarmSituationResp resp = new AlarmSituationResp();

        //查询所有企业数据
        List<CmJoinInfo> cmJoinInfos = cmJoinInfoMapper.selectList(null);
        StringBuffer sb = new StringBuffer();
        List<String> spIds = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(cmJoinInfos)) {
            for (CmJoinInfo cmJoinInfo : cmJoinInfos) {
                spIds.add(cmJoinInfo.getId());
                sb.append(cmJoinInfo.getId()).append(",");
            }
        }
        // 获取当前日期
        LocalDate date = LocalDate.now();

        // 计算近30天的数据
        LocalDate firstDayOfMonth = date.minusDays(30);
        // 不要当天的数据
        LocalDate lastDayOfMonth = date.minusDays(1);

        //查询每个企业+厂商+设备类型+用户类型的报警设备总量
        QueryWrapper<CmStatDevicealarm> queryDevicealarmWrapper = new QueryWrapper<>();
        queryDevicealarmWrapper.lambda().between(CmStatDevicealarm::getDataDate, firstDayOfMonth, lastDayOfMonth).in(CmStatDevicealarm::getSpId, spIds);
        List<CmStatDevicealarm> devicealarms = cmStatDevicealarmMapper.selectList(queryDevicealarmWrapper);
        if (CollectionUtils.isNotEmpty(devicealarms)) {
            int totalAlarm = devicealarms.stream()
                    .mapToInt(CmStatDevicealarm::getNewAlarm)
                    .sum();
            resp.setAlarmNum(totalAlarm);
        } else {
            resp.setAlarmNum(0);
        }

        String spId = sb.toString().substring(0, sb.toString().length() - 1);
        // 查询当天的记录 并过滤掉调试，测试，检测，检定，标定等数据 并且 安装时间开始民用2天 工商7天内的报警不计算    民用-EquipmentType.HOME_GAS_DETECTOR 其他-工商业
        List<PlatformAlarmEquipmentResp> todayAlarmCount = historyAlarmMapper.getTodayAlarmCount(spIds);
        log.info("集团大屏的今天的报警总数：{}", todayAlarmCount);
        if (CollectionUtils.isNotEmpty(todayAlarmCount)) {
            int totalAlarm = todayAlarmCount.stream()
                    .mapToInt(PlatformAlarmEquipmentResp::sumValues)
                    .sum();
            resp.setAlarmNum(resp.getAlarmNum() + totalAlarm);
            resp.setOnDayAlarmNum(totalAlarm);
        } else {
            resp.setOnDayAlarmNum(0);
        }
        log.info("开始调用厨房当日报警接口：{}", spId);
        ConsoleSkAlarmCountListResponse response = consoleSkFeignClient.alarmSosAlarmCountList(spId);
        log.info("调用厨房报警当日接口返回：{}", response);
        if (response != null && response.getCode() == 0 && response.getData() != null && CollectionUtils.isNotEmpty(response.getData().getList())) {
            for (ConsoleSkAlarmCountList skAlarmCountList : response.getData().getList()) {
                resp.setAlarmNum(resp.getAlarmNum() + skAlarmCountList.getTodayAlarmCnt());
                resp.setOnDayAlarmNum(resp.getOnDayAlarmNum() + skAlarmCountList.getTodayAlarmCnt());
            }
        }
        return resp;
    }

    @Override
    public PlatformAlarmSituationResp areaAlarmSituation() {
        PlatformAlarmSituationResp resp = new PlatformAlarmSituationResp();
        //查询当前企业的区域
        List<String> spIds = new ArrayList<>();
        QueryWrapper<CmJoinInfo> getCmJoinWrapper = new QueryWrapper<>();
        getCmJoinWrapper.lambda().eq(CmJoinInfo::getId, ApplicationUtils.getHeaderSpId());
        CmJoinInfo cmJoinInfo = cmJoinInfoMapper.selectOne(getCmJoinWrapper);
        int regionId = 0;
        if (cmJoinInfo != null) {
            regionId = cmJoinInfo.getRegionId();
            QueryWrapper<CmJoinInfo> queryCmJoinWrapper = new QueryWrapper<>();
            queryCmJoinWrapper.lambda().eq(CmJoinInfo::getRegionId, cmJoinInfo.getRegionId());
            //查询区域所有企业
            List<CmJoinInfo> joinInfos = cmJoinInfoMapper.selectList(queryCmJoinWrapper);
            if (CollectionUtils.isNotEmpty(joinInfos)) {
                spIds = joinInfos.stream().map(CmJoinInfo::getId).collect(Collectors.toList());
            } else {
                spIds.add(cmJoinInfo.getId());
            }
        }else {
            QueryWrapper<CmJoinInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(CmJoinInfo::getPId, ApplicationUtils.getHeaderSpId());
            //查询区域所有企业
            List<CmJoinInfo> joinInfoList = cmJoinInfoMapper.selectList(queryWrapper);
            if (CollectionUtils.isNotEmpty(joinInfoList)) {
                CmJoinInfo joinInfo = joinInfoList.get(0);
                regionId = joinInfo.getRegionId();
                QueryWrapper<CmJoinInfo> queryCmJoinWrapper = new QueryWrapper<>();
                queryCmJoinWrapper.lambda().eq(CmJoinInfo::getRegionId, joinInfo.getRegionId());
                //查询区域所有企业
                List<CmJoinInfo> joinInfos = cmJoinInfoMapper.selectList(queryCmJoinWrapper);
                if (CollectionUtils.isNotEmpty(joinInfos)) {
                    spIds = joinInfos.stream().map(CmJoinInfo::getId).collect(Collectors.toList());
                } else {
                    spIds.add(cmJoinInfo.getId());
                }
            } else {
                spIds.add(ApplicationUtils.getHeaderSpId());
            }
        }

        List<CmStatDevicealarm> devicealarms = cmStatDevicealarmMapper.queryPlatformImeiBySpId(spIds);
        if (CollectionUtils.isNotEmpty(devicealarms)) {
            int totalAlarm = devicealarms.stream()
                    .mapToInt(CmStatDevicealarm::getTotalAlarm)
                    .sum();
            resp.setAlarmNum(totalAlarm);
        } else {
            resp.setAlarmNum(0);
        }
        List<DictionaryItemRespDTO> greatAlarmNum = holder.getDictionaryByKey("area_great_alarm_num", "0");
        if (CollectionUtils.isNotEmpty(greatAlarmNum)) {
            for (DictionaryItemRespDTO dictionaryItemRespDTO : greatAlarmNum) {
                if (StringUtils.equals(String.valueOf(regionId), dictionaryItemRespDTO.getName())) {
                    resp.setGreatAlarmNum(Integer.valueOf(dictionaryItemRespDTO.getValue()));
                }
            }
        } else {
            resp.setGreatAlarmNum(23);
        }
        StringBuffer sb = new StringBuffer();
        if (CollectionUtils.isNotEmpty(spIds)) {
            for (String spId : spIds) {
                sb.append(spId).append(",");
            }
        }
        String spId = sb.toString().substring(0, sb.toString().length() - 1);
        // 查询当天的记录 并过滤掉调试，测试，检测，检定，标定等数据 并且 安装时间开始民用2天 工商7天内的报警不计算    民用-EquipmentType.HOME_GAS_DETECTOR 其他-工商业
        List<PlatformAlarmEquipmentResp> todayAlarmCount = historyAlarmMapper.getTodayAlarmCount(spIds);
        log.info("集团大屏的今天的报警总数：{}", todayAlarmCount);
        if (CollectionUtils.isNotEmpty(todayAlarmCount)) {
            int totalAlarm = todayAlarmCount.stream()
                    .mapToInt(PlatformAlarmEquipmentResp::sumValues)
                    .sum();
            resp.setAlarmNum(resp.getAlarmNum() + totalAlarm);
        }
        log.info("开始调用厨房当日报警接口：{}", spId);
        ConsoleSkAlarmCountListResponse response = consoleSkFeignClient.alarmSosAlarmCountList(spId);
        log.info("调用厨房报警当日接口返回：{}", response);
        if (response != null && response.getCode() == 0 && response.getData() != null && CollectionUtils.isNotEmpty(response.getData().getList())) {
            for (ConsoleSkAlarmCountList skAlarmCountList : response.getData().getList()) {
                resp.setAlarmNum(resp.getAlarmNum() + skAlarmCountList.getTodayAlarmCnt());
            }
        }
        return resp;
    }

    @Override
    public AraeAlarmDeviceMonthResp araeAlarmDeviceMonth(ScreenStatisticsMOrGReq req) {

        AraeAlarmDeviceMonthResp resp = new AraeAlarmDeviceMonthResp();
//        //查询每个企业+厂商+设备类型+用户类型的报警设备总量
//        List<CmStatDevicealarm> devicealarms = cmStatDevicealarmMapper.queryPlatformImeiBySpId(null);
//        //查询所有设备数量
//        List<CmStatDevice> cmStatDevices = cmStatDeviceMapper.selectPlatformImeiBySpId(null);
        //查询所有企业
        List<CmJoinInfo> joinInfos = cmJoinInfoMapper.selectList(null);
        // 统计方法
        ToIntFunction<CmJoinInfo> sumFunction = CmJoinInfo::sumValues;
        List<DictionaryItemRespDTO> consumerSum = holder.getDictionaryByKey("area_civil_screen_consumer_sum", "0");
        // m-民用
        if (StringUtils.isNotEmpty(req.getType())) {
            if ("M".equalsIgnoreCase(req.getType())) {
                sumFunction = CmJoinInfo::sumMValues;
                consumerSum = holder.getDictionaryByKey("area_civil_screen_consumer_sum", "0");
            }
            if ("G".equalsIgnoreCase(req.getType())) {
                sumFunction = CmJoinInfo::sumGValues;
                consumerSum = holder.getDictionaryByKey("area_screen_consumer_sum", "0");
            }
        }
        if (CollectionUtils.isNotEmpty(joinInfos)) {
            Map<Integer, List<CmJoinInfo>> integerListMap = joinInfos.stream().collect(Collectors.groupingBy(CmJoinInfo::getRegionId));
            //华东区域设备总数
            Integer eastSums = 0;
            //华北区域设备总数
            Integer northSums = 0;
            //华南区域设备总数
            Integer southSums = 0;
            //华西区域设备总数
            Integer westSums = 0;
            //东北区域设备总数
            Integer northeastSums = 0;
            //华中区域设备总数
            Integer centralSums = 0;
            for (Integer regionId : integerListMap.keySet()) {
                if (1 == regionId) {
                    //获取每个区域的企业id
                    eastSums = integerListMap.get(regionId).stream()
                            .mapToInt(sumFunction)
                            .sum();
                }else if (2 == regionId) {
                    //获取每个区域的企业id
                    westSums = integerListMap.get(regionId).stream()
                            .mapToInt(sumFunction)
                            .sum();
                }else if (3 == regionId) {
                    //获取每个区域的企业id
                    centralSums = integerListMap.get(regionId).stream()
                            .mapToInt(sumFunction)
                            .sum();
                }else if (4 == regionId) {
                    //获取每个区域的企业id
                    northSums = integerListMap.get(regionId).stream()
                            .mapToInt(sumFunction)
                            .sum();
                } else if (5 == regionId) {
                    //获取每个区域的企业id
                    northeastSums = integerListMap.get(regionId).stream()
                            .mapToInt(sumFunction)
                            .sum();
                } else if (6 == regionId) {
                    //获取每个区域的企业id
                    southSums= integerListMap.get(regionId).stream()
                            .mapToInt(sumFunction)
                            .sum();
                }
            }
            log.info("字典:{}的值为", JSONUtil.toJsonStr(consumerSum));
            if (CollectionUtils.isNotEmpty(consumerSum)) {
                for (DictionaryItemRespDTO dictionaryItemRespDTO : consumerSum) {
                    if (StringUtils.equals("1", dictionaryItemRespDTO.getName())) {
                        resp.setEast(new BigDecimal(eastSums).divide(new BigDecimal(dictionaryItemRespDTO.getValue()), 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP));
                    } else if (StringUtils.equals("4", dictionaryItemRespDTO.getName())) {
                        resp.setNorth(new BigDecimal(northSums).divide(new BigDecimal(dictionaryItemRespDTO.getValue()), 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP));
                    } else if (StringUtils.equals("3", dictionaryItemRespDTO.getName())) {
                        resp.setCentral(new BigDecimal(centralSums).divide(new BigDecimal(dictionaryItemRespDTO.getValue()), 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP));
                    } else if (StringUtils.equals("2", dictionaryItemRespDTO.getName())) {
                        resp.setWest(new BigDecimal(westSums).divide(new BigDecimal(dictionaryItemRespDTO.getValue()), 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP));
                    } else if (StringUtils.equals("5", dictionaryItemRespDTO.getName())) {
                        resp.setNortheast(new BigDecimal(northeastSums).divide(new BigDecimal(dictionaryItemRespDTO.getValue()), 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP));
                    } else {
                        resp.setSouth(new BigDecimal(southSums).divide(new BigDecimal(dictionaryItemRespDTO.getValue()), 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP));
                    }
                }
            } else {
                resp.setEast(new BigDecimal(0));
                resp.setNorth(new BigDecimal(0));
                resp.setSouth(new BigDecimal(0));
                resp.setWest(new BigDecimal(0));
                resp.setNortheast(new BigDecimal(0));
                resp.setCentral(new BigDecimal(0));
            }
        }
        return resp;
    }

    @Override
    public CompanyAlarmDeviceResp companyAlarmDevicePie() {
        CompanyAlarmDeviceResp alarmDeviceResp = new CompanyAlarmDeviceResp();
        //没有合并韶关前的集合
        List<CompanyAlarmDeviceListResp> deviceResps = new ArrayList<>();

        //没有合并韶关前的集合民用
        List<CompanyAlarmDeviceListResp> civilDeviceResps = new ArrayList<>();
        //查询当前企业的区域
        List<String> spIds = new ArrayList<>();
        QueryWrapper<CmJoinInfo> getCmJoinWrapper = new QueryWrapper<>();
        getCmJoinWrapper.lambda().eq(CmJoinInfo::getId, ApplicationUtils.getHeaderSpId());
        CmJoinInfo devicealarms = cmJoinInfoMapper.selectOne(getCmJoinWrapper);
        List<CmJoinInfo> joinInfos = new ArrayList<>();
        if (devicealarms != null) {
            QueryWrapper<CmJoinInfo> queryCmJoinWrapper = new QueryWrapper<>();
            queryCmJoinWrapper.lambda().eq(CmJoinInfo::getRegionId, devicealarms.getRegionId());
            //查询区域所有企业
            joinInfos = cmJoinInfoMapper.selectList(queryCmJoinWrapper);
            if (CollectionUtils.isNotEmpty(joinInfos)) {
                spIds = joinInfos.stream().map(CmJoinInfo::getId).collect(Collectors.toList());
            } else {
                spIds.add(devicealarms.getId());
            }
        }else {
            QueryWrapper<CmJoinInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(CmJoinInfo::getPId, ApplicationUtils.getHeaderSpId());
            List<CmJoinInfo> joinInfoList = cmJoinInfoMapper.selectList(queryWrapper);
            if (CollectionUtils.isNotEmpty(joinInfoList)) {
                CmJoinInfo cmJoinInfo = joinInfoList.get(0);
                QueryWrapper<CmJoinInfo> queryCmJoinWrapper = new QueryWrapper<>();
                queryCmJoinWrapper.lambda().eq(CmJoinInfo::getRegionId, cmJoinInfo.getRegionId());
                //查询区域所有企业
                joinInfos = cmJoinInfoMapper.selectList(queryCmJoinWrapper);
                if (CollectionUtils.isNotEmpty(joinInfos)) {
                    spIds = joinInfos.stream().map(CmJoinInfo::getId).collect(Collectors.toList());
                } else {
                    spIds.add(devicealarms.getId());
                }
            } else {
                spIds.add(ApplicationUtils.getHeaderSpId());
            }

        }
        //查询jv下对应的客户数量
        LambdaQueryWrapper<JvInfo> jvQueryWrapper = new LambdaQueryWrapper<>();
        jvQueryWrapper.in(JvInfo::getSpId, spIds).eq(JvInfo::getIsDeleted, 0);
        List<JvInfo> jvInfoList = jvInfoMapper.selectList(jvQueryWrapper);
        //工商业map
        Map<String, Integer> jvInfoMap = new HashMap<>();
        //民用map
        Map<String, Integer> civilJvInfoMap = new HashMap<>();
        //根据企业转为map
        if (CollectionUtils.isNotEmpty(jvInfoList)) {
            jvInfoMap = jvInfoList.stream().collect(Collectors.toMap(JvInfo::getSpId, JvInfo::getUserNums));
            civilJvInfoMap = jvInfoList.stream().collect(Collectors.toMap(JvInfo::getSpId, JvInfo::getCivilUserNums));
        }
        Map<String, SpMapVo> mapVoMap = new HashMap<>();
        //韶关spid
        List<String> spIdList = new ArrayList<>();
        if (StringUtils.isNotEmpty(belongOrgCode)) {
            //根据orgcode批量查询企业信息
            String[] spIdCode = belongOrgCode.split(",");
            List<String> orgCodes = Arrays.stream(spIdCode).collect(Collectors.toList());
            //韶关存在多个子企业需要归属到韶关燃气企业
            List<SpMapVo> spMapVoList = dtuMapper.querySGSpIdOrgCode(orgCodes);
            if( spMapVoList.size()>0 ){
                mapVoMap = spMapVoList.stream().collect(Collectors.toMap(SpMapVo::getSpId, SpMapVo -> SpMapVo));
                spIdList = spMapVoList.stream().map(SpMapVo::getPSpId).collect(Collectors.toList());
            }
        }

        if (CollectionUtils.isNotEmpty(joinInfos)) {
            for (CmJoinInfo joinInfo : joinInfos) {
                //工商业
                CompanyAlarmDeviceListResp deviceResp = new CompanyAlarmDeviceListResp();
                deviceResp.setSpId(joinInfo.getId());
                deviceResp.setSpName(joinInfo.getSpName());
                deviceResp.setUserNums(joinInfo.getGsscUserNumG());
                if (jvInfoMap.containsKey(joinInfo.getId())) {
                    deviceResp.setGasUserNums(jvInfoMap.get(joinInfo.getId()));
                } else {
                    deviceResp.setGasUserNums(0);
                }
                deviceResps.add(deviceResp);
                //民用
                CompanyAlarmDeviceListResp civilDeviceResp = new CompanyAlarmDeviceListResp();
                civilDeviceResp.setSpId(joinInfo.getId());
                civilDeviceResp.setSpName(joinInfo.getSpName());
                //厨房+报警器用户数
                int userNums = joinInfo.getGsscUserNumM() + joinInfo.getSkUserNums();
                civilDeviceResp.setUserNums(userNums);
                if (civilJvInfoMap.containsKey(joinInfo.getId())) {
                    civilDeviceResp.setGasUserNums(civilJvInfoMap.get(joinInfo.getId()));
                } else {
                    civilDeviceResp.setGasUserNums(0);
                }
                civilDeviceResps.add(civilDeviceResp);
            }
            //工商业
            List<CompanyAlarmDeviceListResp> deviceListResps = mergeCompany(mapVoMap, spIdList, deviceResps);
            alarmDeviceResp.setIndustryList(deviceListResps);
            //民用
            List<CompanyAlarmDeviceListResp> civilDeviceListResps = mergeCompany(mapVoMap, spIdList, civilDeviceResps);
            alarmDeviceResp.setCivilList(civilDeviceListResps);
        }

        return alarmDeviceResp;
    }

    public List<CompanyAlarmDeviceListResp> mergeCompany(Map<String, SpMapVo> mapVoMap, List<String> spIdList, List<CompanyAlarmDeviceListResp> deviceResps) {
        Map<String, CompanyAlarmDeviceListResp> deviceRespMap = new HashMap<>();
        //合并韶关后的集合
        List<CompanyAlarmDeviceListResp> deviceRespList = new ArrayList<>();
        //为了合并韶关企业
        for (CompanyAlarmDeviceListResp deviceResp : deviceResps) {
            //表示当前企业是需要合并的主企业
            if (spIdList.contains(deviceResp.getSpId())) {
                //表示当前map中有值
                if (deviceRespMap.containsKey(deviceResp.getSpId())) {
                    CompanyAlarmDeviceListResp alarmDeviceListResp = deviceRespMap.get(deviceResp.getSpId());
                    alarmDeviceListResp.setSpId(deviceResp.getSpId());
                    alarmDeviceListResp.setSpName(deviceResp.getSpName());
                    int userNums = alarmDeviceListResp.getUserNums() + deviceResp.getUserNums();
                    alarmDeviceListResp.setUserNums(userNums);
                    int gasUserNums = alarmDeviceListResp.getGasUserNums() + deviceResp.getGasUserNums();
                    alarmDeviceListResp.setGasUserNums(gasUserNums);
                    if (gasUserNums > 0) {
                        alarmDeviceListResp.setPercentage(new BigDecimal(userNums).divide(new BigDecimal(gasUserNums), 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP));
                    } else {
                        alarmDeviceListResp.setPercentage(new BigDecimal(0));
                    }
                    deviceRespMap.put(deviceResp.getSpId(), alarmDeviceListResp);
                } else {
                    CompanyAlarmDeviceListResp alarmDeviceListResp = new CompanyAlarmDeviceListResp();
                    alarmDeviceListResp.setSpId(deviceResp.getSpId());
                    alarmDeviceListResp.setSpName(deviceResp.getSpName());
                    Integer userNums = deviceResp.getUserNums();
                    alarmDeviceListResp.setUserNums(userNums);
                    Integer gasUserNums = deviceResp.getGasUserNums();
                    alarmDeviceListResp.setGasUserNums(gasUserNums);
                    if (gasUserNums != null && gasUserNums > 0 && userNums != null) {
                        alarmDeviceListResp.setPercentage(new BigDecimal(userNums).divide(new BigDecimal(gasUserNums), 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP));
                    } else {
                        alarmDeviceListResp.setPercentage(new BigDecimal(0));
                    }
                    deviceRespMap.put(deviceResp.getSpId(), alarmDeviceListResp);
                }
            }
            else {
                //表示当前企业需要合并
                if (mapVoMap.containsKey(deviceResp.getSpId())) {
                    SpMapVo spMapVo = mapVoMap.get(deviceResp.getSpId());
                    //表示当前map中有值
                    if (deviceRespMap.containsKey(spMapVo.getPSpId())) {
                        CompanyAlarmDeviceListResp alarmDeviceListResp = deviceRespMap.get(spMapVo.getPSpId());
                        int userNums = alarmDeviceListResp.getUserNums() + deviceResp.getUserNums();
                        alarmDeviceListResp.setUserNums(userNums);
                        int gasUserNums = alarmDeviceListResp.getGasUserNums() + deviceResp.getGasUserNums();
                        alarmDeviceListResp.setGasUserNums(gasUserNums);
                        if (gasUserNums > 0) {
                            alarmDeviceListResp.setPercentage(new BigDecimal(userNums).divide(new BigDecimal(gasUserNums), 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP));
                        } else {
                            alarmDeviceListResp.setPercentage(new BigDecimal(0));
                        }
                        deviceRespMap.put(spMapVo.getPSpId(), alarmDeviceListResp);
                    } else {
                        CompanyAlarmDeviceListResp alarmDeviceListResp = new CompanyAlarmDeviceListResp();
                        alarmDeviceListResp.setSpId(spMapVo.getPSpId());
                        alarmDeviceListResp.setSpName(spMapVo.getPSpName());
                        Integer userNums = deviceResp.getUserNums();
                        alarmDeviceListResp.setUserNums(userNums);
                        Integer gasUserNums = deviceResp.getGasUserNums();
                        alarmDeviceListResp.setGasUserNums(gasUserNums);
                        if (gasUserNums != null && gasUserNums > 0 && userNums != null) {
                            alarmDeviceListResp.setPercentage(new BigDecimal(userNums).divide(new BigDecimal(gasUserNums), 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP));
                        } else {
                            alarmDeviceListResp.setPercentage(new BigDecimal(0));
                        }
                        deviceRespMap.put(spMapVo.getPSpId(), alarmDeviceListResp);
                    }
                } else {
                    //表示正常的不需要合并的企业
                    CompanyAlarmDeviceListResp alarmDeviceListResp = new CompanyAlarmDeviceListResp();
                    alarmDeviceListResp.setSpId(deviceResp.getSpId());
                    alarmDeviceListResp.setSpName(deviceResp.getSpName());
                    Integer userNums = deviceResp.getUserNums();
                    alarmDeviceListResp.setUserNums(userNums);
                    Integer gasUserNums = deviceResp.getGasUserNums();
                    alarmDeviceListResp.setGasUserNums(gasUserNums);
                    if (gasUserNums != null && gasUserNums > 0 && userNums != null) {
                        alarmDeviceListResp.setPercentage(new BigDecimal(userNums).divide(new BigDecimal(gasUserNums), 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP));
                    } else {
                        alarmDeviceListResp.setPercentage(new BigDecimal(0));
                    }
                    deviceRespList.add(alarmDeviceListResp);
                }
            }
        }
        List<String> spIds = new ArrayList<>();
        //代表有需要合并的企业数据
        if (MapUtils.isNotEmpty(deviceRespMap)) {
            for (String spId : deviceRespMap.keySet()) {
                if (!spIds.contains(spId)) {
                    CompanyAlarmDeviceListResp alarmDeviceListResp = deviceRespMap.get(spId);
                    deviceRespList.add(alarmDeviceListResp);
                    spIds.add(spId);
                }

            }
        }
        deviceRespList = deviceRespList.stream().sorted(Comparator.comparing(CompanyAlarmDeviceListResp::getPercentage,Comparator.nullsLast(Comparator.reverseOrder()))).collect(Collectors.toList());
        return deviceRespList;
    }

    @Override
    public AraeAlarmDeviceDayResp araeAlarmDeviceDay() {
        AraeAlarmDeviceDayResp respList = new AraeAlarmDeviceDayResp();
        //查询所有企业
        List<CmJoinInfo> joinInfos = cmJoinInfoMapper.selectList(null);
        if (CollectionUtils.isNotEmpty(joinInfos)) {
            List<String> spIds = joinInfos.stream().map(CmJoinInfo::getId).collect(Collectors.toList());
            //查询所有设备数量
            List<CmStatDevice> cmStatDevices = cmStatDeviceMapper.selectPlatformImeiBySpId(spIds);
            Map<Integer, List<CmJoinInfo>> integerListMap = joinInfos.stream().collect(Collectors.groupingBy(CmJoinInfo::getRegionId));
            //华东区域
            List<String> eastList = new ArrayList<>();
            //华北区域
            List<String> northList = new ArrayList<>();
            //华南区域
            List<String> southList = new ArrayList<>();
            //华西区域
            List<String> westList = new ArrayList<>();
            //东北区域
            List<String> northeastList = new ArrayList<>();
            //华中区域
            List<String> centralList = new ArrayList<>();
            for (Integer key : integerListMap.keySet()) {
                List<CmJoinInfo> cmJoinInfos = integerListMap.get(key);
                if (1 == key) {
                    //获取每个区域的企业id
                    eastList = cmJoinInfos.stream().map(CmJoinInfo::getId).collect(Collectors.toList());
                }else if (2 == key) {
                    //获取每个区域的企业id
                    westList = cmJoinInfos.stream().map(CmJoinInfo::getId).collect(Collectors.toList());
                }else if (3 == key) {
                    //获取每个区域的企业id
                    centralList = cmJoinInfos.stream().map(CmJoinInfo::getId).collect(Collectors.toList());
                }else if (4 == key) {
                    //获取每个区域的企业id
                    northList = cmJoinInfos.stream().map(CmJoinInfo::getId).collect(Collectors.toList());
                }else if (5 == key) {
                    //获取每个区域的企业id
                    northeastList = cmJoinInfos.stream().map(CmJoinInfo::getId).collect(Collectors.toList());
                } else if (6 == key){
                    //获取每个区域的企业id
                    southList = cmJoinInfos.stream().map(CmJoinInfo::getId).collect(Collectors.toList());
                }
            }

            //民用
            List<AraeAlarmDeviceDayCivilResp> civilList = new ArrayList<>();
            //华东区域设备总数
            AraeAlarmDeviceDayCivilResp civileast = new AraeAlarmDeviceDayCivilResp();
            civileast.setArae("华东");
            civileast.setDeviceNum(0);
            civileast.setCivilNum(0);
            //华北区域设备总数
            AraeAlarmDeviceDayCivilResp civilnorth = new AraeAlarmDeviceDayCivilResp();
            civilnorth.setArae("华北");
            civilnorth.setDeviceNum(0);
            civilnorth.setCivilNum(0);
            //华南区域设备总数
            AraeAlarmDeviceDayCivilResp civilsouth = new AraeAlarmDeviceDayCivilResp();
            civilsouth.setArae("华南");
            civilsouth.setDeviceNum(0);
            civilsouth.setCivilNum(0);
            //华西区域设备总数
            AraeAlarmDeviceDayCivilResp civilwest = new AraeAlarmDeviceDayCivilResp();
            civilwest.setArae("华西");
            civilwest.setDeviceNum(0);
            civilwest.setCivilNum(0);
            //东北区域设备总数
            AraeAlarmDeviceDayCivilResp civilnortheast = new AraeAlarmDeviceDayCivilResp();
            civilnortheast.setArae("东北");
            civilnortheast.setDeviceNum(0);
            civilnortheast.setCivilNum(0);
            //华中区域设备总数
            AraeAlarmDeviceDayCivilResp civilcentral = new AraeAlarmDeviceDayCivilResp();
            civilcentral.setArae("华中");
            civilcentral.setDeviceNum(0);
            civilcentral.setCivilNum(0);

            //工商业
            List<AraeAlarmDeviceDayIndustryResp> industryRespList = new ArrayList<>();
            //华东区域设备总数
            AraeAlarmDeviceDayIndustryResp industryeast = new AraeAlarmDeviceDayIndustryResp();
            industryeast.setArae("华东");
            industryeast.setDeviceNum(0);
            industryeast.setIndustryNum(0);
            //华北区域设备总数
            AraeAlarmDeviceDayIndustryResp industrynorth = new AraeAlarmDeviceDayIndustryResp();
            industrynorth.setArae("华北");
            industrynorth.setDeviceNum(0);
            industrynorth.setIndustryNum(0);
            //华南区域设备总数
            AraeAlarmDeviceDayIndustryResp industrysouth = new AraeAlarmDeviceDayIndustryResp();
            industrysouth.setArae("华南");
            industrysouth.setDeviceNum(0);
            industrysouth.setIndustryNum(0);
            //华西区域设备总数
            AraeAlarmDeviceDayIndustryResp industrywest = new AraeAlarmDeviceDayIndustryResp();
            industrywest.setArae("华西");
            industrywest.setDeviceNum(0);
            industrywest.setIndustryNum(0);
            //东北区域设备总数
            AraeAlarmDeviceDayIndustryResp industrynortheast = new AraeAlarmDeviceDayIndustryResp();
            industrynortheast.setArae("东北");
            industrynortheast.setDeviceNum(0);
            industrynortheast.setIndustryNum(0);
            //华中区域设备总数
            AraeAlarmDeviceDayIndustryResp industrycentral = new AraeAlarmDeviceDayIndustryResp();
            industrycentral.setArae("华中");
            industrycentral.setDeviceNum(0);
            industrycentral.setIndustryNum(0);
            if (CollectionUtils.isNotEmpty(cmStatDevices)) {
                //民用总设备数
                Integer civilDeviceNum = 0;
                //工商业总设备数
                Integer industryDeviceNum = 0;
                for (CmStatDevice cmStatDevice : cmStatDevices) {
                    //当用户类型为1时代表民用，其他都是工商业
                    if (StringUtils.equals("1", cmStatDevice.getMyType())) {
                        civilDeviceNum = civilDeviceNum + cmStatDevice.getTotalDevice();
                        if (eastList.contains(cmStatDevice.getSpId())) {
                            //当用户类型为1时代表民用，其他都是工商业
                            civileast.setCivilNum(civileast.getCivilNum() + cmStatDevice.getTotalDevice());
                        } else if (northList.contains(cmStatDevice.getSpId())) {
                            civilnorth.setCivilNum(civilnorth.getCivilNum() + cmStatDevice.getTotalDevice());
                        }else if (southList.contains(cmStatDevice.getSpId())) {
                            civilsouth.setCivilNum(civilsouth.getCivilNum() + cmStatDevice.getTotalDevice());
                        }else if (westList.contains(cmStatDevice.getSpId())) {
                            civilwest.setCivilNum(civilwest.getCivilNum() + cmStatDevice.getTotalDevice());
                        }else if (northeastList.contains(cmStatDevice.getSpId())) {
                            civilnortheast.setCivilNum(civilnortheast.getCivilNum() + cmStatDevice.getTotalDevice());
                        } else if (centralList.contains(cmStatDevice.getSpId())) {
                            civilcentral.setCivilNum(civilcentral.getCivilNum() + cmStatDevice.getTotalDevice());
                        }
                    } else {
                        industryDeviceNum = industryDeviceNum + cmStatDevice.getTotalDevice();
                        if (eastList.contains(cmStatDevice.getSpId())) {
                            industryeast.setIndustryNum(industryeast.getIndustryNum() + cmStatDevice.getTotalDevice());
                        } else if (northList.contains(cmStatDevice.getSpId())) {
                            industrynorth.setIndustryNum(industrynorth.getIndustryNum() + cmStatDevice.getTotalDevice());
                        }else if (southList.contains(cmStatDevice.getSpId())) {
                            industrysouth.setIndustryNum(industrysouth.getIndustryNum() + cmStatDevice.getTotalDevice());
                        }else if (westList.contains(cmStatDevice.getSpId())) {
                            industrywest.setIndustryNum(industrywest.getIndustryNum() + cmStatDevice.getTotalDevice());
                        }else if (northeastList.contains(cmStatDevice.getSpId())) {
                            industrynortheast.setIndustryNum(industrynortheast.getIndustryNum() + cmStatDevice.getTotalDevice());
                        } else if (centralList.contains(cmStatDevice.getSpId())) {
                            industrycentral.setIndustryNum(industrycentral.getIndustryNum() + cmStatDevice.getTotalDevice());
                        }
                    }
                }
                civileast.setDeviceNum(civilDeviceNum);
                civilnorth.setDeviceNum(civilDeviceNum);
                civilsouth.setDeviceNum(civilDeviceNum);
                civilwest.setDeviceNum(civilDeviceNum);
                civilnortheast.setDeviceNum(civilDeviceNum);
                civilcentral.setDeviceNum(civilDeviceNum);
                industryeast.setDeviceNum(industryDeviceNum);
                industrynorth.setDeviceNum(industryDeviceNum);
                industrysouth.setDeviceNum(industryDeviceNum);
                industrywest.setDeviceNum(industryDeviceNum);
                industrynortheast.setDeviceNum(industryDeviceNum);
                industrycentral.setDeviceNum(industryDeviceNum);
            }
            if (civileast.getCivilNum() > 0) {
                civilList.add(civileast);
            }
            if (civilnortheast.getCivilNum() > 0) {
                civilList.add(civilnortheast);
            }
            if (civilnorth.getCivilNum() > 0) {
                civilList.add(civilnorth);
            }
            if (civilsouth.getCivilNum() > 0) {
                civilList.add(civilsouth);
            }
            if (civilwest.getCivilNum() > 0) {
                civilList.add(civilwest);
            }
            if (civilcentral.getCivilNum() > 0) {
                civilList.add(civilcentral);
            }
            respList.setCivilList(civilList);
            if (industryeast.getIndustryNum() > 0) {
                industryRespList.add(industryeast);
            }
            if (industrynorth.getIndustryNum() > 0) {
                industryRespList.add(industrynorth);
            }
            if (industrysouth.getIndustryNum() > 0) {
                industryRespList.add(industrysouth);
            }
            if (industrywest.getIndustryNum() > 0) {
                industryRespList.add(industrywest);
            }
            if (industrynortheast.getIndustryNum() > 0) {
                industryRespList.add(industrynortheast);
            }
            if (industrycentral.getIndustryNum() > 0) {
                industryRespList.add(industrycentral);
            }
            respList.setIndustryList(industryRespList);
        }
        return respList;
    }

    @Override
    public CompanyAlarmDeviceHistogramResp companyAlarmDeviceHistogram() {
        CompanyAlarmDeviceHistogramResp histogramResp = new CompanyAlarmDeviceHistogramResp();
        //没过滤企业的数据工商业
        List<CompanyAlarmDeviceHistogramListResp> histogramRespList = new ArrayList<>();
        //没过滤企业的数据民用
        List<CompanyAlarmDeviceHistogramListResp> civilHistogramRespList = new ArrayList<>();
        log.info("spid的值为:{}", ApplicationUtils.getHeaderSpId());
        //查询当前企业的区域
        List<String> spIds = new ArrayList<>();
        QueryWrapper<CmJoinInfo> getCmJoinWrapper = new QueryWrapper<>();
        getCmJoinWrapper.lambda().eq(CmJoinInfo::getId, ApplicationUtils.getHeaderSpId());
        CmJoinInfo devicealarms = cmJoinInfoMapper.selectOne(getCmJoinWrapper);
        List<CmJoinInfo> joinInfos = new ArrayList<>();
        if (devicealarms != null) {
            QueryWrapper<CmJoinInfo> queryCmJoinWrapper = new QueryWrapper<>();
            queryCmJoinWrapper.lambda().eq(CmJoinInfo::getRegionId, devicealarms.getRegionId());
            //查询区域所有企业
            joinInfos = cmJoinInfoMapper.selectList(queryCmJoinWrapper);
            if (CollectionUtils.isNotEmpty(joinInfos)) {
                spIds = joinInfos.stream().map(CmJoinInfo::getId).collect(Collectors.toList());
            } else {
                spIds.add(devicealarms.getId());
            }
        } else {
            QueryWrapper<CmJoinInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(CmJoinInfo::getPId, ApplicationUtils.getHeaderSpId());
            List<CmJoinInfo> joinInfoList = cmJoinInfoMapper.selectList(queryWrapper);
            if (CollectionUtils.isNotEmpty(joinInfoList)) {
                CmJoinInfo cmJoinInfo = joinInfoList.get(0);
                QueryWrapper<CmJoinInfo> queryCmJoinWrapper = new QueryWrapper<>();
                queryCmJoinWrapper.lambda().eq(CmJoinInfo::getRegionId, cmJoinInfo.getRegionId());
                //查询区域所有企业
                joinInfos = cmJoinInfoMapper.selectList(queryCmJoinWrapper);
                if (CollectionUtils.isNotEmpty(joinInfos)) {
                    spIds = joinInfos.stream().map(CmJoinInfo::getId).collect(Collectors.toList());
                } else {
                    spIds.add(devicealarms.getId());
                }
            } else {
                spIds.add(ApplicationUtils.getHeaderSpId());
            }

        }
        //查询当前区域设备数量
        List<CmStatDevice> cmStatDevices = cmStatDeviceMapper.selectPlatformImeiBySpId(spIds);
        Map<String, List<CmStatDevice>> cmStatDeviceMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(cmStatDevices)) {
            cmStatDeviceMap = cmStatDevices.stream().collect(Collectors.groupingBy(CmStatDevice::getSpId));
        }
        Map<String, SpMapVo> mapVoMap = new HashMap<>();
        //韶关spid
        List<String> spIdList = new ArrayList<>();
        if (StringUtils.isNotEmpty(belongOrgCode)) {
            //根据orgcode批量查询企业信息
            String[] spIdCode = belongOrgCode.split(",");
            List<String> orgCodes = Arrays.stream(spIdCode).collect(Collectors.toList());
            //韶关存在多个子企业需要归属到韶关燃气企业
            List<SpMapVo> spMapVoList = dtuMapper.querySGSpIdOrgCode(orgCodes);
            if( spMapVoList.size()>0 ){
                mapVoMap = spMapVoList.stream().collect(Collectors.toMap(SpMapVo::getSpId, SpMapVo -> SpMapVo));
                spIdList = spMapVoList.stream().map(SpMapVo::getPSpId).collect(Collectors.toList());
            }
        }
        if (CollectionUtils.isNotEmpty(joinInfos)) {
            for (CmJoinInfo joinInfo : joinInfos) {
                //工商业
                CompanyAlarmDeviceHistogramListResp histogramListResp = new CompanyAlarmDeviceHistogramListResp();
                histogramListResp.setSpId(joinInfo.getId());
                histogramListResp.setSpName(joinInfo.getSpName());
                histogramListResp.setDeviceNum(0);
                histogramListResp.setAlarmNum(0);
                //民用
                CompanyAlarmDeviceHistogramListResp civilHistogramListResp = new CompanyAlarmDeviceHistogramListResp();
                civilHistogramListResp.setSpId(joinInfo.getId());
                civilHistogramListResp.setSpName(joinInfo.getSpName());
                civilHistogramListResp.setDeviceNum(0);
                civilHistogramListResp.setAlarmNum(0);
                if (cmStatDeviceMap.containsKey(joinInfo.getId())) {
                    List<CmStatDevice> deviceList = cmStatDeviceMap.get(joinInfo.getId());
                    int totalDevice = 0;
                    for (CmStatDevice cmStatDevice : deviceList) {
                        totalDevice = totalDevice + cmStatDevice.getTotalDevice();
                        if (StringUtils.equals("1", cmStatDevice.getMyType())) {
                            civilHistogramListResp.setAlarmNum(civilHistogramListResp.getAlarmNum() + cmStatDevice.getTotalDevice());
                        }else {
                            histogramListResp.setAlarmNum(histogramListResp.getAlarmNum() + cmStatDevice.getTotalDevice());
                        }
                    }
                    histogramListResp.setDeviceNum(totalDevice);
                    civilHistogramListResp.setDeviceNum(totalDevice);
                }
                if (histogramListResp.getAlarmNum() > 0) {
                    histogramRespList.add(histogramListResp);
                }
                if (civilHistogramListResp.getAlarmNum() > 0) {
                    civilHistogramRespList.add(civilHistogramListResp);
                }
                //工商业
                List<CompanyAlarmDeviceHistogramListResp> histogramListResps = mergeHistoram(mapVoMap, spIdList, histogramRespList);
                histogramResp.setIndustryList(histogramListResps);
                //民用
                List<CompanyAlarmDeviceHistogramListResp> listResps = mergeHistoram(mapVoMap, spIdList, civilHistogramRespList);
                histogramResp.setCivilList(listResps);
            }

        }
        return histogramResp;
    }

    //合并企业数据
    public List<CompanyAlarmDeviceHistogramListResp> mergeHistoram(Map<String, SpMapVo> mapVoMap, List<String> spIdList, List<CompanyAlarmDeviceHistogramListResp> histogramRespList) {
        Map<String, CompanyAlarmDeviceHistogramListResp> histogramRespMap = new HashMap<>();
        //过滤掉合并的企业后的数据
        List<CompanyAlarmDeviceHistogramListResp> deviceHistogramRespList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(histogramRespList)) {
            for (CompanyAlarmDeviceHistogramListResp histogramListResp : histogramRespList) {
                if (spIdList.contains(histogramListResp.getSpId())) {
                    if (histogramRespMap.containsKey(histogramListResp.getSpId())) {
                        CompanyAlarmDeviceHistogramListResp deviceHistogramResp = histogramRespMap.get(histogramListResp.getSpId());
                        deviceHistogramResp.setSpId(histogramListResp.getSpId());
                        deviceHistogramResp.setSpName(histogramListResp.getSpName());
                        deviceHistogramResp.setDeviceNum(deviceHistogramResp.getDeviceNum() + histogramListResp.getDeviceNum());
                        deviceHistogramResp.setAlarmNum(deviceHistogramResp.getAlarmNum() + histogramListResp.getAlarmNum());
                        histogramRespMap.put(histogramListResp.getSpId(), deviceHistogramResp);
                    } else {
                        CompanyAlarmDeviceHistogramListResp deviceHistogramResp = new CompanyAlarmDeviceHistogramListResp();
                        deviceHistogramResp.setSpId(histogramListResp.getSpId());
                        deviceHistogramResp.setSpName(histogramListResp.getSpName());
                        deviceHistogramResp.setDeviceNum(histogramListResp.getDeviceNum());
                        deviceHistogramResp.setAlarmNum(histogramListResp.getAlarmNum());
                        histogramRespMap.put(histogramListResp.getSpId(), deviceHistogramResp);
                    }
                } else {
                    if (mapVoMap.containsKey(histogramListResp.getSpId())) {
                        SpMapVo spMapVo = mapVoMap.get(histogramListResp.getSpId());
                        if (histogramRespMap.containsKey(spMapVo.getPSpId())) {
                            CompanyAlarmDeviceHistogramListResp deviceHistogramResp = histogramRespMap.get(spMapVo.getPSpId());
                            deviceHistogramResp.setDeviceNum(deviceHistogramResp.getDeviceNum() + histogramListResp.getDeviceNum());
                            deviceHistogramResp.setAlarmNum(deviceHistogramResp.getAlarmNum() + histogramListResp.getAlarmNum());
                            histogramRespMap.put(spMapVo.getPSpId(), deviceHistogramResp);
                        } else {
                            CompanyAlarmDeviceHistogramListResp deviceHistogramResp = new CompanyAlarmDeviceHistogramListResp();
                            deviceHistogramResp.setSpId(spMapVo.getPSpId());
                            deviceHistogramResp.setSpName(spMapVo.getPSpName());
                            deviceHistogramResp.setDeviceNum(histogramListResp.getDeviceNum());
                            deviceHistogramResp.setAlarmNum(histogramListResp.getAlarmNum());
                            histogramRespMap.put(spMapVo.getPSpId(), deviceHistogramResp);
                        }
                    } else {
                        CompanyAlarmDeviceHistogramListResp deviceHistogramResp = new CompanyAlarmDeviceHistogramListResp();
                        deviceHistogramResp.setSpId(histogramListResp.getSpId());
                        deviceHistogramResp.setSpName(histogramListResp.getSpName());
                        deviceHistogramResp.setDeviceNum(histogramListResp.getDeviceNum());
                        deviceHistogramResp.setAlarmNum(histogramListResp.getAlarmNum());
                        deviceHistogramRespList.add(deviceHistogramResp);
                    }
                }
            }
        }
        List<String> spIds = new ArrayList<>();
        if (MapUtils.isNotEmpty(histogramRespMap)) {
            for (String spId : histogramRespMap.keySet()) {
                if (!spIds.contains(spId)) {
                    CompanyAlarmDeviceHistogramListResp deviceHistogramResp = histogramRespMap.get(spId);
                    deviceHistogramRespList.add(deviceHistogramResp);
                    spIds.add(spId);
                }
            }
        }
        deviceHistogramRespList = deviceHistogramRespList.stream().sorted(Comparator.comparing(CompanyAlarmDeviceHistogramListResp::getAlarmNum,Comparator.nullsLast(Comparator.reverseOrder()))).collect(Collectors.toList());

        return deviceHistogramRespList;
    }

    @Override
    public List<AraeAlarmDisposeResp> araeAlarmDispose() {
        List<AraeAlarmDisposeResp> respList = new ArrayList<>();

        //查询所有企业
        List<CmJoinInfo> joinInfos = cmJoinInfoMapper.selectList(null);
        if (CollectionUtils.isNotEmpty(joinInfos)) {
            List<String> spIds = joinInfos.stream().map(CmJoinInfo::getId).collect(Collectors.toList());
            Map<Integer, List<CmJoinInfo>> integerListMap = joinInfos.stream().collect(Collectors.groupingBy(CmJoinInfo::getRegionId));
            // 获取当前日期
            LocalDate date = LocalDate.now();

            // 计算近30天的数据
            LocalDate firstDayOfMonth = date.minusDays(30);
            // 不要当天的数据
            LocalDate lastDayOfMonth = date.minusDays(1);

            //查询每个企业+厂商+设备类型+用户类型的报警设备总量
            QueryWrapper<CmStatDevicealarm> queryDevicealarmWrapper = new QueryWrapper<>();
            queryDevicealarmWrapper.lambda().between(CmStatDevicealarm::getDataDate, firstDayOfMonth, lastDayOfMonth).in(CmStatDevicealarm::getSpId, spIds);
            List<CmStatDevicealarm> devicealarms = cmStatDevicealarmMapper.selectList(queryDevicealarmWrapper);
            //华东区域
            List<String> eastList = new ArrayList<>();
            //华北区域
            List<String> northList = new ArrayList<>();
            //华南区域
            List<String> southList = new ArrayList<>();
            //华西区域
            List<String> westList = new ArrayList<>();
            //东北区域
            List<String> northeastList = new ArrayList<>();
            //华中区域
            List<String> centralList = new ArrayList<>();
            for (Integer key : integerListMap.keySet()) {
                List<CmJoinInfo> cmJoinInfos = integerListMap.get(key);
                if (1 == key) {
                    //获取每个区域的企业id
                    eastList = cmJoinInfos.stream().map(CmJoinInfo::getId).collect(Collectors.toList());
                } else if (2 == key) {
                    //获取每个区域的企业id
                    westList = cmJoinInfos.stream().map(CmJoinInfo::getId).collect(Collectors.toList());
                } else if (3 == key) {
                    //获取每个区域的企业id
                    centralList = cmJoinInfos.stream().map(CmJoinInfo::getId).collect(Collectors.toList());
                } else if (4 == key) {
                    //获取每个区域的企业id
                    northList = cmJoinInfos.stream().map(CmJoinInfo::getId).collect(Collectors.toList());
                } else if (5 == key) {
                    //获取每个区域的企业id
                    northeastList = cmJoinInfos.stream().map(CmJoinInfo::getId).collect(Collectors.toList());
                } else if (6 == key) {
                    //获取每个区域的企业id
                    southList = cmJoinInfos.stream().map(CmJoinInfo::getId).collect(Collectors.toList());
                }
            }
            //华东区域设备总数
            AraeAlarmDisposeResp east = new AraeAlarmDisposeResp();
            east.setArae("华东");
            east.setAlarmNum(0);
            east.setProcessedNum(0);
            //总量
            BigDecimal eastAlarm = new BigDecimal(0);
            //处理量
            BigDecimal eastDispose = new BigDecimal(0);
            //华北区域设备总数
            AraeAlarmDisposeResp north = new AraeAlarmDisposeResp();
            north.setArae("华北");
            north.setAlarmNum(0);
            north.setProcessedNum(0);
            //总量
            BigDecimal northAlarm = new BigDecimal(0);
            //处理量
            BigDecimal northDispose = new BigDecimal(0);
            //华南区域设备总数
            AraeAlarmDisposeResp south = new AraeAlarmDisposeResp();
            south.setArae("华南");
            south.setAlarmNum(0);
            south.setProcessedNum(0);
            //总量
            BigDecimal southAlarm = new BigDecimal(0);
            //处理量
            BigDecimal southDispose = new BigDecimal(0);
            //华西区域设备总数
            AraeAlarmDisposeResp west = new AraeAlarmDisposeResp();
            west.setArae("华西");
            west.setAlarmNum(0);
            west.setProcessedNum(0);
            //总量
            BigDecimal westAlarm = new BigDecimal(0);
            //处理量
            BigDecimal westDispose = new BigDecimal(0);
            //东北区域设备总数
            AraeAlarmDisposeResp northeast = new AraeAlarmDisposeResp();
            northeast.setArae("东北");
            northeast.setAlarmNum(0);
            northeast.setProcessedNum(0);
            //总量
            BigDecimal northeastAlarm = new BigDecimal(0);
            //处理量
            BigDecimal northeastDispose = new BigDecimal(0);
            //华中区域设备总数
            AraeAlarmDisposeResp central = new AraeAlarmDisposeResp();
            central.setArae("华中");
            central.setAlarmNum(0);
            central.setProcessedNum(0);
            //总量
            BigDecimal centralAlarm = new BigDecimal(0);
            //处理量
            BigDecimal centralDispose = new BigDecimal(0);
            for (CmStatDevicealarm devicealarm : devicealarms) {
                //log.info("企业为:{}的值为", JSONUtil.toJsonStr(devicealarm.getSpId()));
                if (eastList.contains(devicealarm.getSpId())) {
                    east.setAlarmNum(east.getAlarmNum() + devicealarm.getNewAlarm());
                    east.setProcessedNum(east.getProcessedNum() + devicealarm.getNewAlarmProcessing() + devicealarm.getNewAlarmWork());
                    eastAlarm = eastAlarm.add(new BigDecimal(devicealarm.getNewAlarm()));
                    eastDispose = eastDispose.add(new BigDecimal(devicealarm.getNewAlarmProcessing())).add(new BigDecimal(devicealarm.getNewAlarmWork()).divide(new BigDecimal(2)));
                    //log.info("华东企业为:{}", JSONUtil.toJsonStr(eastAlarm));
                } else if (northList.contains(devicealarm.getSpId())) {
                    north.setAlarmNum(north.getAlarmNum() + devicealarm.getNewAlarm());
                    north.setProcessedNum(north.getProcessedNum() + devicealarm.getNewAlarmProcessing() + devicealarm.getNewAlarmWork());
                    northAlarm = northAlarm.add(new BigDecimal(devicealarm.getNewAlarm()));
                    northDispose = northDispose.add(new BigDecimal(devicealarm.getNewAlarmProcessing())).add(new BigDecimal(devicealarm.getNewAlarmWork()).divide(new BigDecimal(2)));
                    //log.info("华北企业为:{}", JSONUtil.toJsonStr(northAlarm));
                }else if (southList.contains(devicealarm.getSpId())) {
                    south.setAlarmNum(south.getAlarmNum() + devicealarm.getNewAlarm());
                    south.setProcessedNum(south.getProcessedNum() + devicealarm.getNewAlarmProcessing() + devicealarm.getNewAlarmWork());
                    southAlarm = southAlarm.add(new BigDecimal(devicealarm.getNewAlarm()));
                    southDispose = southDispose.add(new BigDecimal(devicealarm.getNewAlarmProcessing())).add(new BigDecimal(devicealarm.getNewAlarmWork()).divide(new BigDecimal(2)));
                    //log.info("华南企业为:{}", JSONUtil.toJsonStr(southAlarm));
                }else if (westList.contains(devicealarm.getSpId())) {
                    west.setAlarmNum(west.getAlarmNum() + devicealarm.getNewAlarm());
                    west.setProcessedNum(west.getProcessedNum() + devicealarm.getNewAlarmProcessing() + devicealarm.getNewAlarmWork());
                    westAlarm = westAlarm.add(new BigDecimal(devicealarm.getNewAlarm()));
                    westDispose = westDispose.add(new BigDecimal(devicealarm.getNewAlarmProcessing())).add(new BigDecimal(devicealarm.getNewAlarmWork()).divide(new BigDecimal(2)));
                    //log.info("华西企业集合为:{}", JSONUtil.toJsonStr(westAlarm));
                }else if (northeastList.contains(devicealarm.getSpId())) {
                    northeast.setAlarmNum(northeast.getAlarmNum() + devicealarm.getNewAlarm());
                    northeast.setProcessedNum(northeast.getProcessedNum() + devicealarm.getNewAlarmProcessing() + devicealarm.getNewAlarmWork());
                    northeastAlarm = northeastAlarm.add(new BigDecimal(devicealarm.getNewAlarm()));
                    northeastDispose = northeastDispose.add(new BigDecimal(devicealarm.getNewAlarmProcessing())).add(new BigDecimal(devicealarm.getNewAlarmWork()).divide(new BigDecimal(2)));
                    //log.info("东北企业为:{}", JSONUtil.toJsonStr(northeastAlarm));
                }else if (centralList.contains(devicealarm.getSpId())) {
                    central.setAlarmNum(central.getAlarmNum() + devicealarm.getNewAlarm());
                    central.setProcessedNum(central.getProcessedNum() + devicealarm.getNewAlarmProcessing() + devicealarm.getNewAlarmWork());
                    centralAlarm = centralAlarm.add(new BigDecimal(devicealarm.getNewAlarm()));
                    centralDispose = centralDispose.add(new BigDecimal(devicealarm.getNewAlarmProcessing())).add(new BigDecimal(devicealarm.getNewAlarmWork()).divide(new BigDecimal(2)));
                    //log.info("华中企业集合为:{}", JSONUtil.toJsonStr(centralAlarm));
                }
            }
            if (!BigDecimal.ZERO.equals(eastAlarm)) {
                if (eastDispose.compareTo(eastAlarm) > 0) {
                    east.setProcessingRate(new BigDecimal(100));
                } else {
                    east.setProcessingRate(eastDispose.divide(eastAlarm, 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP));
                }
                respList.add(east);
            }
            if (!BigDecimal.ZERO.equals(northAlarm)) {
                if (northDispose.compareTo(northAlarm) > 0) {
                    north.setProcessingRate(new BigDecimal(100));
                } else {
                    north.setProcessingRate(northDispose.divide(northAlarm, 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP));
                }
                respList.add(north);
            }
            if (!BigDecimal.ZERO.equals(southAlarm)) {
                if (southDispose.compareTo(southAlarm) > 0) {
                    south.setProcessingRate(new BigDecimal(100));
                } else {
                    south.setProcessingRate(southDispose.divide(southAlarm, 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP));
                }
                respList.add(south);
            }
            if (!BigDecimal.ZERO.equals(westAlarm)) {
                if (westDispose.compareTo(westAlarm) > 0) {
                    west.setProcessingRate(new BigDecimal(100));
                } else {
                    west.setProcessingRate(westDispose.divide(westAlarm, 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP));
                }
                respList.add(west);
            }
            if (!BigDecimal.ZERO.equals(northeastAlarm)) {
                if (northeastDispose.compareTo(northeastAlarm) > 0) {
                    northeast.setProcessingRate(new BigDecimal(100));
                } else {
                    northeast.setProcessingRate(northeastDispose.divide(northeastAlarm, 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP));
                }
                respList.add(northeast);
            }
            if (!BigDecimal.ZERO.equals(centralAlarm)) {
                if (centralDispose.compareTo(centralAlarm) > 0) {
                    central.setProcessingRate(new BigDecimal(100));
                } else {
                    central.setProcessingRate(centralDispose.divide(centralAlarm, 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP));
                }
                respList.add(central);
            }

        }
        return respList;
    }

    @Override
    public List<CompanyAlarmDisposeResp> companyAlarmDispose() {
        //过滤掉合并的企业后的数据
        List<CompanyAlarmDisposeResp> respArrayList = new ArrayList<>();
        //没过滤企业的数据
        List<CompanyAlarmDisposeResp> respList = new ArrayList<>();
        //查询当前企业的区域
        List<String> spIds = new ArrayList<>();
        List<CmJoinInfo> joinInfos = new ArrayList<>();
        QueryWrapper<CmJoinInfo> getCmJoinWrapper = new QueryWrapper<>();
        getCmJoinWrapper.lambda().eq(CmJoinInfo::getId, ApplicationUtils.getHeaderSpId());
        CmJoinInfo cmJoinInfo = cmJoinInfoMapper.selectOne(getCmJoinWrapper);
        if (cmJoinInfo != null) {
            QueryWrapper<CmJoinInfo> queryCmJoinWrapper = new QueryWrapper<>();
            queryCmJoinWrapper.lambda().eq(CmJoinInfo::getRegionId, cmJoinInfo.getRegionId());
            //查询区域所有企业
            joinInfos = cmJoinInfoMapper.selectList(queryCmJoinWrapper);
            if (CollectionUtils.isNotEmpty(joinInfos)) {
                spIds = joinInfos.stream().map(CmJoinInfo::getId).collect(Collectors.toList());
            } else {
                spIds.add(cmJoinInfo.getId());
            }
        }else {
            QueryWrapper<CmJoinInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(CmJoinInfo::getPId, ApplicationUtils.getHeaderSpId());
            List<CmJoinInfo> joinInfoList = cmJoinInfoMapper.selectList(queryWrapper);
            if (CollectionUtils.isNotEmpty(joinInfoList)) {
                CmJoinInfo joinInfo = joinInfoList.get(0);
                QueryWrapper<CmJoinInfo> queryCmJoinWrapper = new QueryWrapper<>();
                queryCmJoinWrapper.lambda().eq(CmJoinInfo::getRegionId, joinInfo.getRegionId());
                //查询区域所有企业
                joinInfos = cmJoinInfoMapper.selectList(queryCmJoinWrapper);
                if (CollectionUtils.isNotEmpty(joinInfos)) {
                    spIds = joinInfos.stream().map(CmJoinInfo::getId).collect(Collectors.toList());
                } else {
                    spIds.add(cmJoinInfo.getId());
                }
            } else {
                spIds.add(ApplicationUtils.getHeaderSpId());
            }

        }
        // 获取当前日期
        LocalDate date = LocalDate.now();

//        // 获取当前月份的第一天
//        LocalDate firstDayOfMonth = date.with(TemporalAdjusters.firstDayOfMonth());
//        // 获取当前月份的最后一天
//        LocalDate lastDayOfMonth = date.with(TemporalAdjusters.lastDayOfMonth());

        // 计算近30天的数据
        LocalDate firstDayOfMonth = date.minusDays(30);
        // 不要当天的数据
        LocalDate lastDayOfMonth = date.minusDays(1);
        //查询每个企业+厂商+设备类型+用户类型的报警设备总量
        QueryWrapper<CmStatDevicealarm> queryDevicealarmWrapper = new QueryWrapper<>();
        queryDevicealarmWrapper.lambda().in(CmStatDevicealarm::getSpId, spIds).between(CmStatDevicealarm::getDataDate, firstDayOfMonth, lastDayOfMonth);
        List<CmStatDevicealarm> devicealarms = cmStatDevicealarmMapper.selectList(queryDevicealarmWrapper);
        Map<String, List<CmStatDevicealarm>> devicealarmMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(devicealarms)) {
            //根据企业进行分组
            devicealarmMap = devicealarms.stream().collect(Collectors.groupingBy(CmStatDevicealarm::getSpId));
        }
        Map<String, SpMapVo> mapVoMap = new HashMap<>();
        //韶关spid
        List<String> spIdList = new ArrayList<>();
        if (StringUtils.isNotEmpty(belongOrgCode)) {
            //根据orgcode批量查询企业信息
            String[] spIdCode = belongOrgCode.split(",");
            List<String> orgCodes = Arrays.stream(spIdCode).collect(Collectors.toList());
            //韶关存在多个子企业需要归属到韶关燃气企业
            List<SpMapVo> spMapVoList = dtuMapper.querySGSpIdOrgCode(orgCodes);
            if( spMapVoList.size()>0 ){
                mapVoMap = spMapVoList.stream().collect(Collectors.toMap(SpMapVo::getSpId, SpMapVo -> SpMapVo));
                spIdList = spMapVoList.stream().map(SpMapVo::getPSpId).collect(Collectors.toList());
            }
        }
        if (CollectionUtils.isNotEmpty(joinInfos)) {
            for (CmJoinInfo joinInfo : joinInfos) {
                CompanyAlarmDisposeResp disposeResp = new CompanyAlarmDisposeResp();
                disposeResp.setSpId(joinInfo.getId());
                disposeResp.setSpName(joinInfo.getSpName());
                Integer alarmNum = 0;
                Integer processedNum = 0;
                BigDecimal centralDispose = new BigDecimal(0);
                if (devicealarmMap.containsKey(joinInfo.getId())) {
                    List<CmStatDevicealarm> devicealarmList = devicealarmMap.get(joinInfo.getId());
                    for (CmStatDevicealarm devicealarm : devicealarmList) {
                        alarmNum = alarmNum + devicealarm.getNewAlarm();
                        processedNum = processedNum + devicealarm.getNewAlarmProcessing() + devicealarm.getNewAlarmWork();
                        centralDispose = centralDispose.add(new BigDecimal(devicealarm.getNewAlarmProcessing())).add(new BigDecimal(devicealarm.getNewAlarmWork()).divide(new BigDecimal(2)));
                    }
                }
                disposeResp.setAlarmNum(alarmNum);
                disposeResp.setProcessedNum(processedNum);
                disposeResp.setCentralDispose(centralDispose);
                respList.add(disposeResp);
            }
           //log.info("企业的集合为:{}", JSONUtil.toJsonStr(respList));
            Map<String, CompanyAlarmDisposeResp> disposeRespMap = new HashMap<>();
            for (CompanyAlarmDisposeResp disposeResp : respList) {
                if (spIdList.contains(disposeResp.getSpId())) {
                    if (disposeRespMap.containsKey(disposeResp.getSpId())) {
                        CompanyAlarmDisposeResp alarmDisposeResp = disposeRespMap.get(disposeResp.getSpId());
                        alarmDisposeResp.setSpId(disposeResp.getSpId());
                        alarmDisposeResp.setSpName(disposeResp.getSpName());
                        int alarm = alarmDisposeResp.getAlarmNum() + disposeResp.getAlarmNum();
                        alarmDisposeResp.setAlarmNum(alarm);
                        alarmDisposeResp.setProcessedNum(alarmDisposeResp.getProcessedNum() + disposeResp.getProcessedNum());
                        BigDecimal centralDispose = alarmDisposeResp.getCentralDispose().add(disposeResp.getCentralDispose());
                        alarmDisposeResp.setCentralDispose(centralDispose);
                        if (alarm > 0) {
                            alarmDisposeResp.setProcessingRate(centralDispose.divide(new BigDecimal(alarm), 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP));
                        } else {
                            alarmDisposeResp.setProcessingRate(new BigDecimal(0));
                        }
                        disposeRespMap.put(disposeResp.getSpId(), alarmDisposeResp);
                    } else {
                        CompanyAlarmDisposeResp alarmDisposeResp = new CompanyAlarmDisposeResp();
                        alarmDisposeResp.setSpId(disposeResp.getSpId());
                        alarmDisposeResp.setSpName(disposeResp.getSpName());
                        Integer alarm = disposeResp.getAlarmNum();
                        alarmDisposeResp.setAlarmNum(alarm);
                        alarmDisposeResp.setProcessedNum(disposeResp.getProcessedNum());
                        BigDecimal centralDispose = disposeResp.getCentralDispose();
                        alarmDisposeResp.setCentralDispose(centralDispose);
                        if (alarm != null && alarm > 0) {
                            alarmDisposeResp.setProcessingRate(centralDispose.divide(new BigDecimal(alarm), 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP));
                        } else {
                            alarmDisposeResp.setProcessingRate(new BigDecimal(0));
                        }
                        disposeRespMap.put(disposeResp.getSpId(), alarmDisposeResp);
                    }
                } else {
                    if (mapVoMap.containsKey(disposeResp.getSpId())) {
                        SpMapVo spMapVo = mapVoMap.get(disposeResp.getSpId());
                        if (disposeRespMap.containsKey(spMapVo.getPSpId())) {
                            CompanyAlarmDisposeResp alarmDisposeResp = disposeRespMap.get(spMapVo.getPSpId());
                            int alarm = alarmDisposeResp.getAlarmNum() + disposeResp.getAlarmNum();
                            alarmDisposeResp.setAlarmNum(alarm);
                            alarmDisposeResp.setProcessedNum(alarmDisposeResp.getProcessedNum() + disposeResp.getProcessedNum());
                            BigDecimal centralDispose = alarmDisposeResp.getCentralDispose().add(disposeResp.getCentralDispose());
                            alarmDisposeResp.setCentralDispose(centralDispose);
                            if (alarm > 0) {
                                alarmDisposeResp.setProcessingRate(centralDispose.divide(new BigDecimal(alarm), 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP));
                            } else {
                                alarmDisposeResp.setProcessingRate(new BigDecimal(0));
                            }
                            disposeRespMap.put(spMapVo.getPSpId(), alarmDisposeResp);
                        } else {
                            CompanyAlarmDisposeResp alarmDisposeResp = new CompanyAlarmDisposeResp();
                            alarmDisposeResp.setSpId(spMapVo.getPSpId());
                            alarmDisposeResp.setSpName(spMapVo.getPSpName());
                            Integer alarm = disposeResp.getAlarmNum();
                            alarmDisposeResp.setAlarmNum(alarm);
                            alarmDisposeResp.setProcessedNum(disposeResp.getProcessedNum());
                            BigDecimal centralDispose = disposeResp.getCentralDispose();
                            alarmDisposeResp.setCentralDispose(centralDispose);
                            if (alarm != null && alarm > 0) {
                                alarmDisposeResp.setProcessingRate(centralDispose.divide(new BigDecimal(alarm), 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP));
                            } else {
                                alarmDisposeResp.setProcessingRate(new BigDecimal(0));
                            }
                            disposeRespMap.put(spMapVo.getPSpId(), alarmDisposeResp);
                        }
                    } else {
                        CompanyAlarmDisposeResp alarmDisposeResp = new CompanyAlarmDisposeResp();
                        alarmDisposeResp.setSpId(disposeResp.getSpId());
                        alarmDisposeResp.setSpName(disposeResp.getSpName());
                        Integer alarm = disposeResp.getAlarmNum();
                        alarmDisposeResp.setAlarmNum(alarm);
                        alarmDisposeResp.setProcessedNum(disposeResp.getProcessedNum());
                        BigDecimal centralDispose = disposeResp.getCentralDispose();
                        alarmDisposeResp.setCentralDispose(centralDispose);
                        if (alarm != null && alarm > 0) {
                            alarmDisposeResp.setProcessingRate(centralDispose.divide(new BigDecimal(alarm), 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP));
                        } else {
                            alarmDisposeResp.setProcessingRate(new BigDecimal(0));
                        }
                        respArrayList.add(alarmDisposeResp);
                    }
                }
            }
            List<String> spIdLists = new ArrayList<>();
            if (MapUtils.isNotEmpty(disposeRespMap)) {
                for (String spId : disposeRespMap.keySet()) {
                    if (!spIdLists.contains(spId)) {
                        CompanyAlarmDisposeResp disposeResp = disposeRespMap.get(spId);
                        respArrayList.add(disposeResp);
                        spIdLists.add(spId);
                    }
                }
            }
        }
        respArrayList = respArrayList.stream().sorted(Comparator.comparing(CompanyAlarmDisposeResp::getAlarmNum,Comparator.nullsLast(Comparator.reverseOrder()))).collect(Collectors.toList());
        // 取前5个元素
        List<CompanyAlarmDisposeResp> top6 = respArrayList.subList(0, Math.min(6, respList.size()));
        return top6;
    }

    @Override
    public List<AraeStateResp> araeState() {
        List<AraeStateResp> stateRespList = new ArrayList<>();
        //根据spid查询企业
        List<CmJoinInfo> joinInfos = cmJoinInfoMapper.selectList(null);
        if (CollectionUtils.isNotEmpty(joinInfos)) {
            //根据区域id进下分组
            Map<Integer, List<CmJoinInfo>> regionMap = joinInfos.stream().collect(Collectors.groupingBy(CmJoinInfo::getRegionId));
            StringBuffer sb = new StringBuffer();
            for (CmJoinInfo cmJoinInfo : joinInfos) {
                sb.append(cmJoinInfo.getId()).append(",");
            }
            //查询所有报警和故障的企业信息
            List<DeviceState> devicealarms = deviceStateMapper.queryDeviceState(null);
            List<PlatformAraeStateResp> araeStateResps = new ArrayList<>();
            //故障
            //List<String> breakdown = new ArrayList<>();
            //报警
            List<String> warning = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(devicealarms)) {
                //故障
//                breakdown = devicealarms.stream().filter(equipmentVo -> {
//                    return equipmentVo.getDeviceStatus() == 4;
//                }).map(DeviceState::getSpId).collect(Collectors.toList());
                //报警
                warning = devicealarms.stream().filter(equipmentVo -> {
                    return equipmentVo.getDeviceStatus() == 2 || equipmentVo.getDeviceStatus() == 3
                            || equipmentVo.getDeviceStatus() == 6;
                }).map(DeviceState::getSpId).collect(Collectors.toList());
            }
            //查询厨房数据
            String spId = sb.toString().substring(0, sb.toString().length() - 1);
            ConsoleSkDeviceRunListRequest request = new ConsoleSkDeviceRunListRequest();
            request.setSpId(spId);
            log.info("厨房设备运行统计请求:{}", JSONUtil.toJsonStr(request));
            ConsoleSkDeviceRunListResponse runListResponse = consoleSkFeignClient.alarmSOSDeviceRunList(request);
            log.info("厨房设备运行统计返回:{}", JSONUtil.toJsonStr(runListResponse));
            if (runListResponse != null && runListResponse.getCode() == 0 && runListResponse.getData() != null && CollectionUtils.isNotEmpty(runListResponse.getData().getList())) {
                for (ConsoleSkDeviceRunStatisticsData statisticsData : runListResponse.getData().getList()) {
//                    if (statisticsData.getFaultCnt() > 0) {
//                        breakdown.add(statisticsData.getSpId());
//                    }
                    if (statisticsData.getAlarmCnt() > 0) {
                        warning.add(statisticsData.getSpId());
                    }
                }
            }

            for (Integer region : regionMap.keySet()) {
                PlatformAraeStateResp stateResp = new PlatformAraeStateResp();
                stateResp.setRegionId(region);
                for (CmJoinInfo cmJoinInfo : regionMap.get(region)) {
//                    if (breakdown.contains(cmJoinInfo.getId())) {
//                        stateResp.setBreakdownState("故障");
//                    }
                    if (warning.contains(cmJoinInfo.getId())) {
                        stateResp.setWarningState("告警");
                    }
                }
                if (StringUtils.isNotEmpty(stateResp.getWarningState())) {
                    araeStateResps.add(stateResp);
                }
            }
            for (PlatformAraeStateResp araeStateResp : araeStateResps) {
                AraeStateResp stateResp = new AraeStateResp();
                stateResp.setRegionId(araeStateResp.getRegionId());
                stateResp.setRegionName(ScreenStatisticsAreaEnum.getStateName(araeStateResp.getRegionId()));
                if (StringUtils.isNotEmpty(araeStateResp.getWarningState())) {
                    stateResp.setState(2);
                }
//                else {
//                    stateResp.setState(1);
//                }
                stateRespList.add(stateResp);
            }
        }

        return stateRespList;
    }

    @Override
    public List<CompanyStateResp> companyState() {
        //没过滤企业的数据
        List<CompanyStateResp> respList = new ArrayList<>();
        //查询当前企业的区域
        List<String> spIds = new ArrayList<>();
        List<CmJoinInfo> joinInfos = new ArrayList<>();
        QueryWrapper<CmJoinInfo> getCmJoinWrapper = new QueryWrapper<>();
        getCmJoinWrapper.lambda().eq(CmJoinInfo::getId, ApplicationUtils.getHeaderSpId());
        CmJoinInfo cmJoinInfo = cmJoinInfoMapper.selectOne(getCmJoinWrapper);
        if (cmJoinInfo != null) {
            QueryWrapper<CmJoinInfo> queryCmJoinWrapper = new QueryWrapper<>();
            queryCmJoinWrapper.lambda().eq(CmJoinInfo::getRegionId, cmJoinInfo.getRegionId());
            //查询区域所有企业
            joinInfos = cmJoinInfoMapper.selectList(queryCmJoinWrapper);
            if (CollectionUtils.isNotEmpty(joinInfos)) {
                spIds = joinInfos.stream().map(CmJoinInfo::getId).collect(Collectors.toList());
            } else {
                spIds.add(cmJoinInfo.getId());
            }
        }else {
            QueryWrapper<CmJoinInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(CmJoinInfo::getId, ApplicationUtils.getHeaderSpId());
            List<CmJoinInfo> joinInfoList = cmJoinInfoMapper.selectList(queryWrapper);
            if (CollectionUtils.isNotEmpty(joinInfoList)) {
                CmJoinInfo joinInfo = joinInfoList.get(0);
                QueryWrapper<CmJoinInfo> queryCmJoinWrapper = new QueryWrapper<>();
                queryCmJoinWrapper.lambda().eq(CmJoinInfo::getRegionId, joinInfo.getRegionId());
                //查询区域所有企业
                joinInfos = cmJoinInfoMapper.selectList(queryCmJoinWrapper);
                if (CollectionUtils.isNotEmpty(joinInfos)) {
                    spIds = joinInfos.stream().map(CmJoinInfo::getId).collect(Collectors.toList());
                } else {
                    spIds.add(cmJoinInfo.getId());
                }
            } else {
                spIds.add(ApplicationUtils.getHeaderSpId());
            }

        }
        //查询所有报警和故障的企业信息
        List<DeviceState> devicealarms = deviceStateMapper.queryDeviceState(spIds);
        //故障
        List<String> breakdown = new ArrayList<>();
        //报警
        List<String> warning = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(devicealarms)) {
            //故障
            breakdown = devicealarms.stream().filter(equipmentVo -> {
                return equipmentVo.getDeviceStatus() == 4;
            }).map(DeviceState::getSpId).collect(Collectors.toList());
            //报警
            warning = devicealarms.stream().filter(equipmentVo -> {
                return equipmentVo.getDeviceStatus() == 2 || equipmentVo.getDeviceStatus() == 3
                        || equipmentVo.getDeviceStatus() == 6;
            }).map(DeviceState::getSpId).collect(Collectors.toList());
        }
        StringBuffer sb = new StringBuffer();
        for (String spId : spIds) {
            sb.append(spId).append(",");
        }
        //查询厨房数据
        String spId = sb.toString().substring(0, sb.toString().length() - 1);
        ConsoleSkDeviceRunListRequest request = new ConsoleSkDeviceRunListRequest();
        request.setSpId(spId);
        log.info("厨房设备运行统计请求:{}", JSONUtil.toJsonStr(request));
        ConsoleSkDeviceRunListResponse runListResponse = consoleSkFeignClient.alarmSOSDeviceRunList(request);
        log.info("厨房设备运行统计返回:{}", JSONUtil.toJsonStr(runListResponse));
        if (runListResponse != null && runListResponse.getCode() == 0 && runListResponse.getData() != null && CollectionUtils.isNotEmpty(runListResponse.getData().getList())) {
            for (ConsoleSkDeviceRunStatisticsData statisticsData : runListResponse.getData().getList()) {
                if (statisticsData.getFaultCnt() > 0) {
                    if (!breakdown.contains(statisticsData.getSpId())) {
                        breakdown.add(statisticsData.getSpId());
                    }
                }
                if (statisticsData.getAlarmCnt() > 0) {
                    if (!warning.contains(statisticsData.getSpId())) {
                        warning.add(statisticsData.getSpId());
                    }
                }
            }
        }
        Map<String, SpMapVo> mapVoMap = new HashMap<>();
        //韶关spid
        List<String> spIdList = new ArrayList<>();
        if (StringUtils.isNotEmpty(belongOrgCode)) {
            //根据orgcode批量查询企业信息
            String[] spIdCode = belongOrgCode.split(",");
            List<String> orgCodes = Arrays.stream(spIdCode).collect(Collectors.toList());
            //韶关存在多个子企业需要归属到韶关燃气企业
            List<SpMapVo> spMapVoList = dtuMapper.querySGSpIdOrgCode(orgCodes);
            if( spMapVoList.size()>0 ){
                mapVoMap = spMapVoList.stream().collect(Collectors.toMap(SpMapVo::getSpId, SpMapVo -> SpMapVo));
                spIdList = spMapVoList.stream().map(SpMapVo::getPSpId).collect(Collectors.toList());
            }
        }
        Map<String, PlatformAraeStateResp> disposeRespMap = new HashMap<>();
        List<PlatformAraeStateResp> araeStateResps = new ArrayList<>();
        for (CmJoinInfo joinInfo : joinInfos) {
            //父企业是否存在
            if (spIdList.contains(joinInfo.getId())) {
                if (disposeRespMap.containsKey(joinInfo.getId())) {
                    PlatformAraeStateResp araeStateResp = disposeRespMap.get(joinInfo.getId());
                    araeStateResp.setSpId(joinInfo.getId());
                    araeStateResp.setSpName(joinInfo.getSpName());
                    if (breakdown.contains(joinInfo.getId())) {
                        araeStateResp.setBreakdownState("故障");
                    }
                    if (warning.contains(joinInfo.getId())) {
                        araeStateResp.setWarningState("告警");
                    }
                    if (StringUtils.isNotEmpty(araeStateResp.getBreakdownState()) || StringUtils.isNotEmpty(araeStateResp.getWarningState())) {
                        disposeRespMap.put(joinInfo.getId(), araeStateResp);
                    }
                } else {
                    PlatformAraeStateResp araeStateResp = new PlatformAraeStateResp();
                    araeStateResp.setSpId(joinInfo.getId());
                    araeStateResp.setSpName(joinInfo.getSpName());
                    if (breakdown.contains(joinInfo.getId())) {
                        araeStateResp.setBreakdownState("故障");
                    }
                    if (warning.contains(joinInfo.getId())) {
                        araeStateResp.setWarningState("告警");
                    }
                    if (StringUtils.isNotEmpty(araeStateResp.getBreakdownState()) || StringUtils.isNotEmpty(araeStateResp.getWarningState())) {
                        disposeRespMap.put(joinInfo.getId(), araeStateResp);
                    }
                }
            } else {
                //判断子企业是否存在
                if (mapVoMap.containsKey(joinInfo.getId())) {
                    SpMapVo spMapVo = mapVoMap.get(joinInfo.getId());
                    if (disposeRespMap.containsKey(spMapVo.getPSpId())) {
                        PlatformAraeStateResp araeStateResp = disposeRespMap.get(joinInfo.getId());
                        araeStateResp.setSpId(spMapVo.getPSpId());
                        araeStateResp.setSpName(spMapVo.getPSpName());
                        if (breakdown.contains(joinInfo.getId())) {
                            araeStateResp.setBreakdownState("故障");
                        }
                        if (warning.contains(joinInfo.getId())) {
                            araeStateResp.setWarningState("告警");
                        }
                        if (StringUtils.isNotEmpty(araeStateResp.getBreakdownState()) || StringUtils.isNotEmpty(araeStateResp.getWarningState())) {
                            disposeRespMap.put(spMapVo.getPSpId(), araeStateResp);
                        }
                    } else {
                        PlatformAraeStateResp araeStateResp = new PlatformAraeStateResp();
                        araeStateResp.setSpId(spMapVo.getPSpId());
                        araeStateResp.setSpName(spMapVo.getPSpName());
                        if (breakdown.contains(joinInfo.getId())) {
                            araeStateResp.setBreakdownState("故障");
                        }
                        if (warning.contains(joinInfo.getId())) {
                            araeStateResp.setWarningState("告警");
                        }
                        if (StringUtils.isNotEmpty(araeStateResp.getBreakdownState()) || StringUtils.isNotEmpty(araeStateResp.getWarningState())) {
                            disposeRespMap.put(spMapVo.getPSpId(), araeStateResp);
                        }
                    }
                } else {
                    PlatformAraeStateResp araeStateResp = new PlatformAraeStateResp();
                    araeStateResp.setSpId(joinInfo.getId());
                    araeStateResp.setSpName(joinInfo.getSpName());
                    if (breakdown.contains(joinInfo.getId())) {
                        araeStateResp.setBreakdownState("故障");
                    }
                    if (warning.contains(joinInfo.getId())) {
                        araeStateResp.setWarningState("告警");
                    }
                    if (StringUtils.isNotEmpty(araeStateResp.getBreakdownState()) || StringUtils.isNotEmpty(araeStateResp.getWarningState())) {
                        araeStateResps.add(araeStateResp);
                    }
                }
            }
        }
        List<String> spIdLists = new ArrayList<>();
        if (MapUtils.isNotEmpty(disposeRespMap)) {
            for (String spid : disposeRespMap.keySet()) {
                if (!spIdLists.contains(spid)) {
                    PlatformAraeStateResp disposeResp = disposeRespMap.get(spid);
                    araeStateResps.add(disposeResp);
                    spIdLists.add(spid);
                }
            }
        }
        log.info("araeStateResps状态为:{}", JSONUtil.toJsonStr(araeStateResps));
        if (CollectionUtils.isNotEmpty(araeStateResps)) {
            for (PlatformAraeStateResp araeStateResp : araeStateResps) {
                CompanyStateResp stateResp = new CompanyStateResp();
                stateResp.setSpId(araeStateResp.getSpId());
                stateResp.setSpName(araeStateResp.getSpName());
                if (StringUtils.isNotEmpty(araeStateResp.getWarningState())) {
                    stateResp.setState(2);
                } else {
                    stateResp.setState(1);
                }
                respList.add(stateResp);
            }
        }
        return respList;
    }

    @Override
    public PageUtil<PlatformCompanyManageResp> companyManage(ScreenCompanyManageReq req) {
        PageUtil<PlatformCompanyManageResp> respPageUtil = new PageUtil<>();
        // respPageUtil.setColumns(PageColumnConst.add(asstConsumerListTitles, asstConsumerListIndices));
        List<PlatformCompanyManageResp> respList = new ArrayList<>();
        //查询所有企业
        QueryWrapper<CompanyEntry> getCmJoinWrapper = new QueryWrapper<>();
        getCmJoinWrapper.lambda().eq(CompanyEntry::getIsDeleted, 0);
        List<CompanyEntry> companyEntryList = companyMapper.selectList(getCmJoinWrapper);
        List<String> list1 = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(companyEntryList)) {
            list1 = companyEntryList.stream().map(CompanyEntry::getSpId).collect(Collectors.toList());
        }
        List<String> list2 = new ArrayList<>();
        //查询e网通用户的权限
        UserBackend workingUser = ApplicationUtils.getWorkingUser();
        JSONObject availableSps = provider.getAvailableSp(workingUser.getToken());
        if (ObjectUtils.isEmpty(availableSps)) {
            respPageUtil.setList(respList);
            return respPageUtil;
        }
        availableSps.getJSONArray("items").forEach(sp -> {
            JSONObject spObj = JSONUtil.parseObj(sp);
            list2.add(spObj.getStr("id"));
        });
        List<String> spIds = list1.stream()
                .filter(list2::contains)
                .collect(Collectors.toList());
        String body = provider.queryCompany(spIds, req.getSpName(), req.getScale(), targetUrl);
        List<QueryCompanyResp> companyResps = JSONArray.parseArray(body, QueryCompanyResp.class);
        //查询企业下的设备
        QueryWrapper<Dtu> queryDtuWrapper = new QueryWrapper<>();
        queryDtuWrapper.lambda().eq(Dtu::getIsDeleted, 0).in(Dtu::getSpId, spIds);
        List<Dtu> dtuList = dtuMapper.selectList(queryDtuWrapper);
        //根据企业进行分组算设备数量合安装数量
        Map<String, List<Dtu>> dtuMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(dtuList)) {
            dtuMap = dtuList.stream().collect(Collectors.groupingBy(Dtu::getSpId));
        }
        Map<String, PlatformCompanyManageResp> respHashMap = new HashMap<>();
        List<PlatformCompanyManageResp> roots = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(companyResps)) {
            for (QueryCompanyResp companyResp : companyResps) {
                PlatformCompanyManageResp resp = new PlatformCompanyManageResp();
                resp.setSpId(companyResp.getSpId());
                resp.setPId(companyResp.getPId());
                resp.setSpName(companyResp.getSpName());
                resp.setScale(companyResp.getScale());
                resp.setScaleStr(companyResp.getScaleStr());
                resp.setSpShortName(companyResp.getSpShortName());
                resp.setCreateTime(companyResp.getCreateTime());
                if (dtuMap.containsKey(companyResp.getSpId())) {
                    List<Dtu> dtus = dtuMap.get(companyResp.getSpId());
                    resp.setImeiSum(dtus.size());
                    //过滤掉没绑定客户的属于安装了设备
                    List<Dtu> appPushs = dtus.stream().filter(dtu -> {
                        return dtu.getConsumerId() > 0;
                    }).collect(Collectors.toList());
                    resp.setInstallSum(appPushs.size());
                }
                respHashMap.put(companyResp.getSpId(), resp);
                respList.add(resp);
            }
            for (PlatformCompanyManageResp node : respList) {
                PlatformCompanyManageResp current = respHashMap.get(node.getSpId());
                String parentId = node.getPId();

                if (StringUtils.isNotEmpty(parentId)) {
                    PlatformCompanyManageResp parent = respHashMap.get(parentId);
                    if (parent != null) {
                        if (CollectionUtils.isNotEmpty(parent.getChildren())) {
                            parent.getChildren().add(current);
                            if (current.getImeiSum() != null) {
                                if (parent.getImeiSum() != null) {
                                    parent.setImeiSum(parent.getImeiSum() + current.getImeiSum());
                                } else {
                                    parent.setImeiSum(current.getImeiSum());
                                }
                            }
                            if (current.getInstallSum() != null) {
                                if (parent.getInstallSum() != null) {
                                    parent.setInstallSum(parent.getInstallSum() + current.getInstallSum());
                                } else {
                                    parent.setInstallSum(current.getInstallSum());
                                }
                            }
                        } else {
                            List<PlatformCompanyManageResp> children = new ArrayList<>();
                            children.add(current);
                            parent.setChildren(children);
                            if (current.getImeiSum() != null) {
                                if (parent.getImeiSum() != null) {
                                    parent.setImeiSum(parent.getImeiSum() + current.getImeiSum());
                                } else {
                                    parent.setImeiSum(current.getImeiSum());
                                }
                            }
                            if (current.getInstallSum() != null) {
                                if (parent.getInstallSum() != null) {
                                    parent.setInstallSum(parent.getInstallSum() + current.getInstallSum());
                                } else {
                                    parent.setInstallSum(current.getInstallSum());
                                }
                            }
                        }
                    } else {
                        roots.add(current);
                    }
                } else {
                    roots.add(current);
                }
            }
        }

        respPageUtil.setList(roots);
        //根据条件查询e网通企业管理接口
        return respPageUtil;
    }

    @Override
    public DeviceSpreadResp deviceSpread(ScreenStatisticsReq req) {
        DeviceSpreadResp spreadResp = new DeviceSpreadResp();
        QueryWrapper<CmJoinInfo> queryWrapper = new QueryWrapper<>();
        List<CmJoinInfo> joinInfos;
        if (req.getGroupScreen() == 2) {
            List<String> spIds = areaPermission();
            queryWrapper.lambda().in(CmJoinInfo::getId, spIds);
            joinInfos = cmJoinInfoMapper.selectList(queryWrapper);
        } else {
            //查询所有企业
            joinInfos = cmJoinInfoMapper.selectList(null);
        }

        Map<String, SpMapVo> mapVoMap = new HashMap<>();
        //String spId = null;
        List<String> spIdList = new ArrayList<>();
        if (StringUtils.isNotEmpty(belongOrgCode)) {
            //根据orgcode批量查询企业信息
            String[] spIdCode = belongOrgCode.split(",");
            List<String> orgCodes = Arrays.stream(spIdCode).collect(Collectors.toList());
            //韶关存在多个子企业需要归属到韶关燃气企业
            List<SpMapVo> spMapVoList = dtuMapper.querySGSpIdOrgCode(orgCodes);
            if( spMapVoList.size()>0 ){
                mapVoMap = spMapVoList.stream().collect(Collectors.toMap(SpMapVo::getSpId, SpMapVo -> SpMapVo));
                spIdList = spMapVoList.stream().map(SpMapVo::getPSpId).collect(Collectors.toList());
            }
        }
        if (CollectionUtils.isNotEmpty(joinInfos)) {
            List<String> spIds = joinInfos.stream().map(CmJoinInfo::getId).collect(Collectors.toList());
            Map<String, String> joinMap = joinInfos.stream().collect(Collectors.toMap(CmJoinInfo::getId, CmJoinInfo::getSpName));
            //没有合并韶关前的集合
            List<CompanyAlarmDeviceListResp> deviceResps = new ArrayList<>();
            //没有合并韶关前的集合民用
            List<CompanyAlarmDeviceListResp> civilDeviceResps = new ArrayList<>();
            //查询jv下对应的客户数量
            LambdaQueryWrapper<JvInfo> jvQueryWrapper = new LambdaQueryWrapper<>();
            jvQueryWrapper.in(JvInfo::getSpId, spIds).eq(JvInfo::getIsDeleted, 0);
            List<JvInfo> jvInfoList = jvInfoMapper.selectList(jvQueryWrapper);
            //工商业map
            Map<String, Integer> jvInfoMap = new HashMap<>();
            //民用map
            Map<String, Integer> civilJvInfoMap = new HashMap<>();
            //根据企业转为map
            if (CollectionUtils.isNotEmpty(jvInfoList)) {
                jvInfoMap = jvInfoList.stream().collect(Collectors.toMap(JvInfo::getSpId, JvInfo::getUserNums));
                civilJvInfoMap = jvInfoList.stream().collect(Collectors.toMap(JvInfo::getSpId, JvInfo::getCivilUserNums));
            }
            for (CmJoinInfo joinInfo : joinInfos) {
                //工商业
                CompanyAlarmDeviceListResp deviceResp = new CompanyAlarmDeviceListResp();
                deviceResp.setSpId(joinInfo.getId());
                deviceResp.setSpName(joinInfo.getSpName());
                deviceResp.setUserNums(joinInfo.getGsscUserNumG());
                if (jvInfoMap.containsKey(joinInfo.getId())) {
                    deviceResp.setGasUserNums(jvInfoMap.get(joinInfo.getId()));
                } else {
                    deviceResp.setGasUserNums(0);
                }
                deviceResps.add(deviceResp);
                //民用
                CompanyAlarmDeviceListResp civilDeviceResp = new CompanyAlarmDeviceListResp();
                civilDeviceResp.setSpId(joinInfo.getId());
                civilDeviceResp.setSpName(joinInfo.getSpName());
                //厨房+报警器用户数
                int userNums = joinInfo.getGsscUserNumM() + joinInfo.getSkUserNums();
                civilDeviceResp.setUserNums(userNums);
                if (civilJvInfoMap.containsKey(joinInfo.getId())) {
                    civilDeviceResp.setGasUserNums(civilJvInfoMap.get(joinInfo.getId()));
                } else {
                    civilDeviceResp.setGasUserNums(0);
                }
                civilDeviceResps.add(civilDeviceResp);
            }
            //工商业
            List<CompanyAlarmDeviceListResp> deviceListResps = mergeCompany(mapVoMap, spIdList, deviceResps);
            Map<String, CompanyAlarmDeviceListResp> deviceListRespMap = new HashMap<>();
            if (CollectionUtils.isNotEmpty(deviceListResps)) {
                deviceListRespMap = deviceListResps.stream().collect(Collectors.toMap(CompanyAlarmDeviceListResp::getSpId, CompanyAlarmDeviceListResp -> CompanyAlarmDeviceListResp, (e1,e2) -> e1));
            }
            //民用
            List<CompanyAlarmDeviceListResp> civilDeviceListResps = mergeCompany(mapVoMap, spIdList, civilDeviceResps);
            Map<String, CompanyAlarmDeviceListResp> civilDeviceListRespMap = new HashMap<>();
            if (CollectionUtils.isNotEmpty(civilDeviceListResps)) {
                civilDeviceListRespMap = civilDeviceListResps.stream().collect(Collectors.toMap(CompanyAlarmDeviceListResp::getSpId, CompanyAlarmDeviceListResp -> CompanyAlarmDeviceListResp, (e1,e2) -> e1));
            }

            List<CmStatDevice> cmStatDevices = cmStatDeviceMapper.selectPlatformImeiSumBySpId(spIds);
            if (CollectionUtils.isNotEmpty(cmStatDevices)) {
                //民用
                Map<String, DeviceSpreadCivilResp> spreadCivilRespMap = new HashMap<>();
                List<DeviceSpreadCivilResp> spreadCivilRespList = new ArrayList<>();
                //工商业
                Map<String, DeviceSpreadIndustryResp> spreadIndustryRespMap = new HashMap<>();
                List<DeviceSpreadIndustryResp> spreadIndustryRespList = new ArrayList<>();
                for (CmStatDevice cmStatDevice : cmStatDevices) {
                    //查询当前企业是否为韶关子企业，是的话需要合并
                    if (mapVoMap.containsKey(cmStatDevice.getSpId())) {
                        SpMapVo spMapVo = mapVoMap.get(cmStatDevice.getSpId());
                        //当用户类型为1时代表民用，其他都是工商业
                        if (StringUtils.equals("1", cmStatDevice.getMyType())) {
                            if (spreadCivilRespMap.containsKey(spMapVo.getPSpId())) {
                                DeviceSpreadCivilResp spreadCivilResp = spreadCivilRespMap.get(spMapVo.getPSpId());
                                spreadCivilResp.setCivilNum(spreadCivilResp.getCivilNum() + cmStatDevice.getTotalDevice());
                                spreadCivilRespMap.put(spMapVo.getPSpId(), spreadCivilResp);
                            } else {
                                DeviceSpreadCivilResp spreadCivilResp = new DeviceSpreadCivilResp();
                                spreadCivilResp.setSpId(spMapVo.getPSpId());
                                spreadCivilResp.setSpName(spMapVo.getPSpName());
                                spreadCivilResp.setCivilNum(cmStatDevice.getTotalDevice());
                                spreadCivilRespMap.put(spMapVo.getPSpId(), spreadCivilResp);
                            }
                        } else {
                            if (spreadIndustryRespMap.containsKey(spMapVo.getPSpId())) {
                                DeviceSpreadIndustryResp spreadIndustryResp = spreadIndustryRespMap.get(spMapVo.getPSpId());
                                spreadIndustryResp.setIndustryNum(spreadIndustryResp.getIndustryNum() + cmStatDevice.getTotalDevice());
                                spreadIndustryRespMap.put(spMapVo.getPSpId(), spreadIndustryResp);
                            } else {
                                DeviceSpreadIndustryResp spreadIndustryResp = new DeviceSpreadIndustryResp();
                                spreadIndustryResp.setSpId(spMapVo.getPSpId());
                                spreadIndustryResp.setSpName(spMapVo.getPSpName());
                                spreadIndustryResp.setIndustryNum(cmStatDevice.getTotalDevice());
                                spreadIndustryRespMap.put(spMapVo.getPSpId(), spreadIndustryResp);
                            }
                        }

                    } else {
                        //判断当前企业是否为韶关，是则合并
                        if (CollectionUtils.isNotEmpty(spIdList) && spIdList.contains(cmStatDevice.getSpId())) {
                            //当用户类型为1时代表民用，其他都是工商业
                            if (StringUtils.equals("1", cmStatDevice.getMyType())) {
                                if (spreadCivilRespMap.containsKey(cmStatDevice.getSpId())) {
                                    DeviceSpreadCivilResp spreadCivilResp = spreadCivilRespMap.get(cmStatDevice.getSpId());
                                    spreadCivilResp.setCivilNum(spreadCivilResp.getCivilNum() + cmStatDevice.getTotalDevice());
                                    spreadCivilRespMap.put(cmStatDevice.getSpId(), spreadCivilResp);
                                } else {
                                    DeviceSpreadIndustryResp spreadIndustryResp = new DeviceSpreadIndustryResp();
                                    spreadIndustryResp.setSpId(cmStatDevice.getSpId());
                                    spreadIndustryResp.setSpName(joinMap.get(cmStatDevice.getSpId()));
                                    spreadIndustryResp.setIndustryNum(cmStatDevice.getTotalDevice());
                                    spreadIndustryRespMap.put(cmStatDevice.getSpId(), spreadIndustryResp);
                                }
                            }

                        } else {
                            //当用户类型为1时代表民用，其他都是工商业
                            if (StringUtils.equals("1", cmStatDevice.getMyType())) {
                                DeviceSpreadCivilResp spreadCivilResp = new DeviceSpreadCivilResp();
                                spreadCivilResp.setSpId(cmStatDevice.getSpId());
                                spreadCivilResp.setSpName(joinMap.get(cmStatDevice.getSpId()));
                                spreadCivilResp.setCivilNum(cmStatDevice.getTotalDevice());
                                spreadCivilRespList.add(spreadCivilResp);
                            } else {
                                DeviceSpreadIndustryResp spreadIndustryResp = new DeviceSpreadIndustryResp();
                                spreadIndustryResp.setSpId(cmStatDevice.getSpId());
                                spreadIndustryResp.setSpName(joinMap.get(cmStatDevice.getSpId()));
                                spreadIndustryResp.setIndustryNum(cmStatDevice.getTotalDevice());
                                spreadIndustryRespList.add(spreadIndustryResp);
                            }

                        }
                    }
                }
                List<String> spIdLists = new ArrayList<>();
                if (MapUtils.isNotEmpty(spreadCivilRespMap)) {
                    for (String spid : spreadCivilRespMap.keySet()) {
                        if (!spIdLists.contains(spid)) {
                            spreadCivilRespList.add(spreadCivilRespMap.get(spid));
                            spIdLists.add(spid);
                        }
                    }
                }
                //根据民用设备总量降序
                spreadCivilRespList = spreadCivilRespList.stream().sorted(Comparator.comparing(DeviceSpreadCivilResp::getCivilNum,Comparator.nullsLast(Comparator.reverseOrder()))).collect(Collectors.toList());
                // 取前5个元素
                List<DeviceSpreadCivilResp> civilRespList = spreadCivilRespList.subList(0, Math.min(5, spreadCivilRespList.size()));
                if (CollectionUtils.isNotEmpty(civilRespList)) {
                    for (DeviceSpreadCivilResp spreadCivilResp : civilRespList) {
                        if (civilDeviceListRespMap.containsKey(spreadCivilResp.getSpId())) {
                            CompanyAlarmDeviceListResp deviceListResp = civilDeviceListRespMap.get(spreadCivilResp.getSpId());
                            spreadCivilResp.setUserNums(deviceListResp.getUserNums());
                            spreadCivilResp.setGasUserNums(deviceListResp.getGasUserNums());
                            spreadCivilResp.setPercentage(deviceListResp.getPercentage());
                        }
                    }
                }
                spreadResp.setCivilList(civilRespList);
                List<String> civilSpIds = new ArrayList<>();
                if (MapUtils.isNotEmpty(spreadIndustryRespMap)) {
                    for (String spid : spreadIndustryRespMap.keySet()) {
                        if (!civilSpIds.contains(spid)) {
                            spreadIndustryRespList.add(spreadIndustryRespMap.get(spid));
                            civilSpIds.add(spid);
                        }
                    }
                }
                //根据工商业设备总量降序
                spreadIndustryRespList = spreadIndustryRespList.stream().sorted(Comparator.comparing(DeviceSpreadIndustryResp::getIndustryNum,Comparator.nullsLast(Comparator.reverseOrder()))).collect(Collectors.toList());
                // 取前5个元素
                List<DeviceSpreadIndustryResp> industryResps = spreadIndustryRespList.subList(0, Math.min(5, spreadIndustryRespList.size()));
                if (CollectionUtils.isNotEmpty(industryResps)) {
                    for (DeviceSpreadIndustryResp industryResp : industryResps) {
                        if (deviceListRespMap.containsKey(industryResp.getSpId())) {
                            CompanyAlarmDeviceListResp deviceListResp = deviceListRespMap.get(industryResp.getSpId());
                            industryResp.setUserNums(deviceListResp.getUserNums());
                            industryResp.setGasUserNums(deviceListResp.getGasUserNums());
                            industryResp.setPercentage(deviceListResp.getPercentage());
                        }
                    }
                }
                spreadResp.setIndustryList(industryResps);
            }
        }
        return spreadResp;
    }

    @Override
    public DeviceBrokenDataResp deviceBrokenData(ScreenStatisticsReq req) {
        DeviceBrokenDataResp brokenDataResp = new DeviceBrokenDataResp();
        List<DeviceBrokenDataListResp> cmStatDevices = new ArrayList<>();
        List<String> spIds = new ArrayList<>();
        if (req.getGroupScreen() == 2) {
            spIds = areaPermission();
        } else {
            //查询所有企业
            List<CmJoinInfo> joinInfos = cmJoinInfoMapper.selectList(null);
            if (CollectionUtils.isNotEmpty(joinInfos)) {
                spIds = joinInfos.stream().map(CmJoinInfo::getId).collect(Collectors.toList());
            }
        }
        //故障设备数量
        Integer brokenDeviceCount = historyBrokenMapper.deviceBrokenCount(spIds);
        brokenDataResp.setBrokenDeviceCount(brokenDeviceCount);
        //查询所有设备数量
        QueryWrapper<Dtu> dtuWrapper = new QueryWrapper<>();
        dtuWrapper.lambda().in(Dtu::getSpId, spIds).eq(Dtu::getIsDeleted, 0);
        List<Dtu> dtuList = dtuMapper.selectList(dtuWrapper);
        if (CollectionUtils.isNotEmpty(dtuList)) {
            brokenDataResp.setDeviceCount(dtuList.size());
            BigDecimal brokenRate = new BigDecimal(brokenDeviceCount).divide(new BigDecimal(dtuList.size()), 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);
            brokenDataResp.setBrokenRate(brokenRate);
        } else {
            brokenDataResp.setDeviceCount(0);
            brokenDataResp.setBrokenRate(new BigDecimal(0));
        }
        //log.info("故障spIds请求:{}", JSONUtil.toJsonStr(spIds));
        List<DeviceBrokenDataVO> brokenDataVOS = historyBrokenMapper.deviceBrokenData(spIds);
        //log.info("故障设备数量请求:{}", JSONUtil.toJsonStr(brokenDataVOS));
        //设备总量
        Integer brokenCount = 0;
        if (CollectionUtils.isNotEmpty(brokenDataVOS)) {
            //合并数据
            Map<String, DeviceBrokenDataVO> dataVOMap = new HashMap<>();
            List<DeviceBrokenDataVO> brokenDataVOList = new ArrayList<>();
            for (DeviceBrokenDataVO brokenDataVO : brokenDataVOS) {
                if (StringUtils.isNotEmpty(brokenDataVO.getReason())) {
                    String[] reason = brokenDataVO.getReason().split(";");
                    if (dataVOMap.containsKey(reason[0])) {
                        DeviceBrokenDataVO dataVO = dataVOMap.get(reason[0]);
                        dataVO.setBrokenSum(dataVO.getBrokenSum() + brokenDataVO.getBrokenSum());
                        dataVOMap.put(reason[0], dataVO);
                    } else {
                        dataVOMap.put(reason[0], brokenDataVO);
                    }
                } else {
                    brokenDataVOList.add(brokenDataVO);
                }
            }
            if (MapUtils.isNotEmpty(dataVOMap)) {
                for (String reason : dataVOMap.keySet()) {
                    brokenDataVOList.add(dataVOMap.get(reason));
                }
            }
            //根据故障数量进行降序
            brokenDataVOList = brokenDataVOList.stream().sorted(Comparator.comparing(DeviceBrokenDataVO::getBrokenSum,Comparator.nullsLast(Comparator.reverseOrder()))).collect(Collectors.toList());
            //log.info("故障合并排序后的设备数量请求:{}", JSONUtil.toJsonStr(brokenDataVOList));
            int i = 0;
            DeviceBrokenDataListResp dataListResp = new DeviceBrokenDataListResp();
            dataListResp.setBrokenType("其他");
            dataListResp.setBrokenNum(0);
            for (DeviceBrokenDataVO brokenDataVO : brokenDataVOList) {
                brokenCount = brokenCount + brokenDataVO.getBrokenSum();
                if (i < 5) {
                    i = i +1;
                    DeviceBrokenDataListResp brokenDataListResp = new DeviceBrokenDataListResp();
                    if (StringUtils.isNotEmpty(brokenDataVO.getReason())) {
                        brokenDataListResp.setBrokenType(brokenDataVO.getReason());
                    } else {
                        brokenDataListResp.setBrokenType(brokenDataVO.getValveBrokenInfo());
                    }
                    brokenDataListResp.setBrokenNum(brokenDataVO.getBrokenSum());
                    cmStatDevices.add(brokenDataListResp);
                } else {
                    dataListResp.setBrokenNum(dataListResp.getBrokenNum() + brokenDataVO.getBrokenSum());
                }
            }
            if (dataListResp.getBrokenNum() > 0) {
                cmStatDevices.add(dataListResp);
            }
            for (DeviceBrokenDataListResp cmStatDevice : cmStatDevices) {
                BigDecimal divide = new BigDecimal(cmStatDevice.getBrokenNum()).divide(new BigDecimal(brokenCount), 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);
                cmStatDevice.setBrokenRate(divide);
            }
        }
        brokenDataResp.setBrokenCount(brokenCount);
        brokenDataResp.setBrokenList(cmStatDevices);
        return brokenDataResp;
    }

    @Override
    public BrokenDeviceSituationResp brokenDeviceSituation() {
        BrokenDeviceSituationResp resp = new BrokenDeviceSituationResp();

        //查询所有企业数据
        List<CmJoinInfo> cmJoinInfos = cmJoinInfoMapper.selectList(null);
        List<String> spIds = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(cmJoinInfos)) {
            for (CmJoinInfo cmJoinInfo : cmJoinInfos) {
                spIds.add(cmJoinInfo.getId());
            }
        }
        // 获取当前日期
        LocalDate date = LocalDate.now();
        // 计算近30天的数据
        LocalDate firstDayOfMonth = date.minusDays(30);
        // 不要当天的数据
        LocalDate lastDayOfMonth = date.minusDays(1);

        //查询30天内设备总量
        QueryWrapper<CmStatDevice> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().between(CmStatDevice::getDataDate, firstDayOfMonth, lastDayOfMonth).in(CmStatDevice::getSpId, spIds);
        List<CmStatDevice> devicealarms = cmStatDeviceMapper.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(devicealarms)) {
            int totalDevice = devicealarms.stream()
                    .mapToInt(CmStatDevice::getNewDevice)
                    .sum();
            resp.setDeviceNum(totalDevice);
        } else {
            resp.setDeviceNum(0);
        }
        // 查询当天新增的设备数
        Integer onDayDeviceNum = dtuMapper.selectOnDayDeviceNum(spIds);
        log.info("集团大屏的今天的报警总数：{}", onDayDeviceNum);
        if (onDayDeviceNum != null) {
            resp.setDeviceNum(resp.getDeviceNum() + onDayDeviceNum);
            resp.setOnDayDeviceNum(onDayDeviceNum);
        } else {
            resp.setOnDayDeviceNum(0);
        }

        //查询30天内故障总数
        Integer brokenCount = historyBrokenMapper.quantumBrokenCount(spIds, firstDayOfMonth, lastDayOfMonth);
        if (brokenCount != null) {
            resp.setBrokenNum(brokenCount);
        } else {
            resp.setBrokenNum(0);
        }

        //查询当日故障总数
        Integer quantumed = historyBrokenMapper.quantumBrokenCount(spIds, date, date);
        if (quantumed != null) {
            resp.setBrokenNum(resp.getBrokenNum() + quantumed);
            resp.setOnDayBrokenNum(quantumed);
        } else {
            resp.setOnDayBrokenNum(quantumed);
        }
        return resp;
    }

    /**
     * 根据当前用户获取用户权限
     * @return
     */
    public List<String> permission() {
        //查询所有企业
        List<CmJoinInfo> joinInfos = cmJoinInfoMapper.selectList(null);
        List<String> list1 = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(joinInfos)) {
            list1 = joinInfos.stream().map(CmJoinInfo::getId).collect(Collectors.toList());
        }
        List<String> list2 = new ArrayList<>();
        //查询e网通用户的权限
        UserBackend workingUser = ApplicationUtils.getWorkingUser();
        JSONObject availableSps = provider.getAvailableSp(workingUser.getToken());
        if (ObjectUtils.isEmpty(availableSps)) {
            return list2;
        }
        availableSps.getJSONArray("items").forEach(sp -> {
            JSONObject spObj = JSONUtil.parseObj(sp);
            list2.add(spObj.getStr("id"));
        });
        List<String> spIds = list1.stream()
                .filter(list2::contains)
                .collect(Collectors.toList());
        return spIds;
    }

    /**
     * 根据当前企业获取当前区域所有企业
     * @return
     */
    public List<String> areaPermission() {
        //查询当前企业的区域
        List<String> spIds = new ArrayList<>();
        String spId = ApplicationUtils.getHeaderSpId();
        log.info("当前企业spId的值为:{}", spId);
        QueryWrapper<CmJoinInfo> getCmJoinWrapper = new QueryWrapper<>();
        getCmJoinWrapper.lambda().eq(CmJoinInfo::getId, spId);
        CmJoinInfo cmJoinInfo = cmJoinInfoMapper.selectOne(getCmJoinWrapper);
        if (cmJoinInfo != null) {
            QueryWrapper<CmJoinInfo> queryCmJoinWrapper = new QueryWrapper<>();
            queryCmJoinWrapper.lambda().eq(CmJoinInfo::getRegionId, cmJoinInfo.getRegionId());
            //查询区域所有企业
            List<CmJoinInfo> joinInfos = cmJoinInfoMapper.selectList(queryCmJoinWrapper);
            if (CollectionUtils.isNotEmpty(joinInfos)) {
                spIds = joinInfos.stream().map(CmJoinInfo::getId).collect(Collectors.toList());
            } else {
                spIds.add(cmJoinInfo.getId());
            }
        }else {
            QueryWrapper<CmJoinInfo> queryCmJoinWrapper = new QueryWrapper<>();
            queryCmJoinWrapper.lambda().eq(CmJoinInfo::getPId, spId);
            //查询区域所有企业
            List<CmJoinInfo> joinInfos = cmJoinInfoMapper.selectList(queryCmJoinWrapper);
            if (CollectionUtils.isNotEmpty(joinInfos)) {
                CmJoinInfo joinInfo = joinInfos.get(0);
                QueryWrapper<CmJoinInfo> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().eq(CmJoinInfo::getRegionId, joinInfo.getRegionId());
                //查询区域所有企业
                List<CmJoinInfo> joinInfoList = cmJoinInfoMapper.selectList(queryWrapper);
                if (CollectionUtils.isNotEmpty(joinInfoList)) {
                    spIds = joinInfoList.stream().map(CmJoinInfo::getId).collect(Collectors.toList());
                } else {
                    spIds.add(cmJoinInfo.getId());
                }
            } else {
                spIds.add(spId);
            }
        }

        return spIds;
    }
}
